我有2个这样的数组:
数组一:
[
[
"id" => 1234
"name" => "John"
],
[
"id" => 1235
"name" => "doe"
]
]
第二个数组:
[
[
"age" => 12
],
[
"age" => 13
]
]
我已经尝试过使用array_reduce
,array_map
或array_merge_recursive
并将其组合在一起,但是结果仍然不匹配。
如何使两个数组如下所示?
[
[
"id" => 1234
"name" => "John"
"age" => 12
],
[
"id" => 1235
"name" => "doe"
"age" => 13
]
]
请帮助我。谢谢
答案 0 :(得分:6)
答案 1 :(得分:1)
您可以像这样使用array_merge:
<?php
$array = array(
["id" => "1",
"name" => "denba"
],
["id" => "1",
"name" => "chpa7"
],
);
$ages = array(
["age" => "15",
],
["age" => "17",
],
);
foreach($array as $key => $value){
$array[$key]=array_merge($array[$key], $ages[$key]);
}
var_dump($array);
/*output:
array(2) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["name"]=>
string(5) "denba"
["age"]=>
string(2) "15"
}
[1]=>
array(3) {
["id"]=>
string(1) "1"
["name"]=>
string(5) "chpa7"
["age"]=>
string(2) "17"
}
}
*/
答案 2 :(得分:0)
您可以迭代第一个数组,并在尊重索引匹配的情况下与第二个数组合并
$merged =[];
foreach($a as $k => $val){
array_push($merged,array_merge($val,$b[$k]));
}
print_r($merged);