How to create an array in PHP that with json_encode() becomes a thing with following structure:
Array(
[1] => Array(
[id] => 1
[data] => 45
)
[2] => Array(
[id] => 3
[data] => 54
)
);
How to create an array in PHP that with json_encode() becomes a thing with following structure:
Array(
[1] => Array(
[id] => 1
[data] => 45
)
[2] => Array(
[id] => 3
[data] => 54
)
);
I played with your code to get it working :
function findKey($array, $keySearch)
{
foreach ($array as $key => $item) {
if ($key == $keySearch) {
echo 'yes, it exists';
return true;
} elseif (is_array($item) && findKey($item, $keySearch)) {
return true;
}
}
return false;
}
Don't use strcmp :)
function custom_sort($a, $b) {
return $a['revenue_certificate'] - $b['revenue_certificate'];
}
usort($data_array, 'custom_sort');
custom_sort should return a negative, 0, positive value when $a < $b, $a == $b, $a < $b respectively (just as strcmp does BTW).
That is not valid JSON. The structure you are looking for would be something like:
[
{"key1": ["package1", "package2", "package3"]},
{"key2": ["package1", "package2", "package3", "package4"}]
^ An array as the value to the key "key1", "key2", etc..
]
At the PHP side, you would need something like:
$arr[$key]
= <new array>$arr[$key]
json_encode($arr)
You can do it like this, do the calculation from the innermost of the array. Check the demo.
<?php
function f(&$array)
{
foreach($array as $k => &$v)
{
if(is_array($v))
{
if(count($v) == count($v, 1))
{
unset($array[$k]);
if($k == 'sum')
{
$v = array_sum($v);
$array[] = $v;
}elseif($k == 'multiply'){
$v = array_product($v);
$array[] = $v;
}else{
foreach($v as $vv)
$array[] = $vv;
}
}else
f($v);
}
}
}
while(count($array) != count($array, 1))
{
f($array);
}
print_r($array);
Noteļ¼
traverse array from outer to inner
traverse array from inner to outer
Try something like this: