Suganya Rajasekar Suganya Rajasekar - 4 months ago 16
PHP Question

How to merge two array where one array is dynamic nested values

I'm having two arrays like this

$whole_orders

Array
(
[2] => Array
(
[0] => Array
(
[id] => 3
[food_id] => 1
)

)

[1] => Array
(
[0] => Array
(
[id] => 2
[food_id] => 2
)

[1] => Array
(
[id] => 1
[food_id] => 1
)

)

)


And $array

Array
(
[2] => Array
(
[0] => Array
(
[count] => 1
[subtotal] => 103.42
[tax] => 18.42
)

)

[1] => Array
(
[0] => Array
(
[count] => 2
[subtotal] => 303.42
[tax] => 38.42
)

)

)


Here I'm having two arrays such as
$whole_orders & $array
from which I need to merge the
$array
values into the
$whole_orders
..

And the
$whole_orders
having nested values which are dynamic..

Finally My array should be like this..

Array
(
[2] => Array
(
[0] => Array
(
[id] => 3
[food_id] => 1
)

[1] => Array
(
[count] => 1
[subtotal] => 103.42
[tax] => 18.42
)
)

[1] => Array
(
[0] => Array
(
[id] => 2
[food_id] => 2
)

[1] => Array
(
[id] => 1
[food_id] => 1
)
[2] => Array
(
[count] => 2
[subtotal] => 303.42
[tax] => 38.42
)
)

)


It should append nested values of
$whole_orders
array's..

If you think that my title is not correct please change it..

Thanks in advance..

EDIT
I tried something like this

foreach($whole_orders as $kys => $vls){
foreach($array as $kys_in => $vls_in){
if($kys === $kys_in){
$whole_orders[$kys+1]['tax'] = $vls_in['tax'];
}
}
}


But It didn't work for me it retrieve the results something like this while printing that
$whole_orders


Array
(
[2] => Array
(
[0] => Array
(
[id] => 3
[food_id] => 1
)

[tax] =>
)

[1] => Array
(
[0] => Array
(
[id] => 2
[food_id] => 2
)

[1] => Array
(
[id] => 1
[food_id] => 1
)

)

[3] => Array
(
[tax] =>
)

)

Answer

Just do this it will achieve you desire output ,but when if the count is save for both array

foreach($array as $arrayKey => $arrayValue){
    foreach($arrayValue as $key => $value){
        $whole_orders[$arrayKey][] = $value;
    }
}

print_r($whole_orders);