我需要一种方法来合并几个数组(可能大约 8 个)并对任何重复的键或子键求和。
例如:
$arr1 = [
"Friday" => ["Breakfast" => 32, "Lunch" => 45],
"Sunday" => ["Lunch" => 12]
];
$arr2 = [
"Sunday" => ["Breakfast" => 7, "Lunch" => 3],
"Monday" => ["Breakfast" => 12]
];
$arr3 = [
"Monday" => ["Breakfast" => 31]
];
输出应该是这样的:
array (
'Friday' =>
array (
'Breakfast' => 32,
'Lunch' => 45,
),
'Sunday' =>
array (
'Lunch' => 15,
'Breakfast' => 7,
),
'Monday' =>
array (
'Breakfast' => 43,
),
);
我怎么能把这个结合起来?我试过使用array_map()
.
但是对于像这样的多维数组,这似乎失败了。也尝试过使用foreach()
,但这变得非常复杂。
这是我的尝试:
$total = array_map( function( $arr1, $arr2, $arr3 ){
return( $arr1 + $arr2 + $arr3 );
}, $arr1, $arr2, $arr3 );