我想在 PHP 中组合两个多维数组。
打印_r($array_a):
Array
(
[0] => Array
(
[0] => A
[1] => 0
[2] => 1047
)
[1] => Array
(
[0] => B
[1] => 0
[2] => 279
)
[2] => Array
(
[0] => C
[1] => 0
[2] => 68
)
[3] => Array
(
[0] => D
[1] => 0
[2] => 4
)
)
打印_r($array_b):
Array
(
[0] => Array
(
[0] => A
[1] => 76
[2] => 0
)
[1] => Array
(
[0] => B
[1] => 170
[2] => 0
)
[2] => Array
(
[0] => C
[1] => 15
[2] => 0
)
[3] => Array
(
[0] => D
[1] => 210
[2] => 0
)
[4] => Array
(
[0] => E
[1] => 287
[2] => 0
)
)
然后合并它,结果应该是这样的:
Array
(
[0] => Array
(
[0] => A
[1] => 76
[2] => 1047
)
[1] => Array
(
[0] => B
[1] => 170
[2] => 279
)
[2] => Array
(
[0] => C
[1] => 15
[2] => 68
)
[3] => Array
(
[0] => D
[1] => 210
[2] => 4
)
[4] => Array
(
[0] => E
[1] => 287
[2] => 0
)
)
所以逻辑关键是根据每个数组的第一个值(A,B,C,D)合并两个数组。如果有一个数组只属于其中一个数组(例如,array_b 上的“E”),我只需添加它们。我试过这个:
foreach($array_a as $a=>$array_now){
foreach($array_b as $b=>$array_before){
if($array_now[0] == $array_before[0]){
$array_a[$a] = [$array_before[0], $array_before[1], $array_now[2]];
}
}
}
但我似乎无法添加缺失的数组($array_b 中的第 5 个数组,其中包含“E”)。