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 );
Advertisement
Answer
Try this solution. You can add any count of arrays. But keep names as $arr1-$maxArraysCount
$arr1 = array( "Friday" => array( "Breakfast" => 32, "Lunch" => 45 ), "Sunday" => array( "Lunch" => 12 ) ); $arr2 = array( "Sunday" => array( "Breakfast" => 7, "Lunch" => 3 ), "Monday" => array( "Breakfast" => 12 ) ); $arr3 = array( "Monday" => array( "Breakfast" => 31 ) ); $maxArraysCount = 8; $return = array(); for($i = 1; $i < $maxArraysCount; $i++){ $arr = 'arr' . $i; if(isset($$arr) && is_array($$arr)){ foreach ($$arr as $day => $value) { foreach ($value as $eat => $count) { if(!isset($return[$day][$eat])) $return[$day][$eat] = 0; $return[$day][$eat] = $count + $return[$day][$eat]; } } } } echo "<pre>";print_r($return);
Here is output:
Array ( [Friday] => Array ( [Breakfast] => 32 [Lunch] => 45 ) [Sunday] => Array ( [Lunch] => 15 [Breakfast] => 7 ) [Monday] => Array ( [Breakfast] => 43 ) )