I'm needing a way to merge several arrays ( probably around 8 ) and sum any duplicate keys or sub-keys.
For example:
$arr1 = [
"Friday" => ["Breakfast" => 32, "Lunch" => 45],
"Sunday" => ["Lunch" => 12]
];
$arr2 = [
"Sunday" => ["Breakfast" => 7, "Lunch" => 3],
"Monday" => ["Breakfast" => 12]
];
$arr3 = [
"Monday" => ["Breakfast" => 31]
];
And the output should be something like this:
array (
'Friday' =>
array (
'Breakfast' => 32,
'Lunch' => 45,
),
'Sunday' =>
array (
'Lunch' => 15,
'Breakfast' => 7,
),
'Monday' =>
array (
'Breakfast' => 43,
),
);
How could I combine this? I've tried using array_map()
.
But that seemed to fail with multidimensional arrays like this. Also tried using foreach()
, but that got pretty convoluted.
Here's my attempt:
$total = array_map( function( $arr1, $arr2, $arr3 ){
return( $arr1 + $arr2 + $arr3 );
}, $arr1, $arr2, $arr3 );