我有两个数组。 array1
包含用户的详细信息,而array2
具有个人详细信息。如何使用foreach引用将array2
合并到array1
中?
$array1 = [
['id'=> 1,'name'=>'John Sena', 'lastname'=>'Jonn'],
['id'=> 2,'name'=>'Rock', 'lastname'=>'Rock Sena']
];
$array2 = [
['id'=>1, 'company'=>'Warner Brother'], ['id'=>2, 'company'=>'Metro'],['id'=>'1', 'Address'=>'USA']
];
答案 0 :(得分:1)
您可以尝试使用此代码,而不用编写foreach的代码:
$res = array_merge($array1, $array2);
$res = array_reduce($res, function($acc, $item) {
$acc[$item['id']] = isset($acc[$item['id']]) ?
array_merge($acc[$item['id']], $item) :
$acc[$item['id']] = $item;
return $acc;
});
答案 1 :(得分:0)
您可以使用array_merge,在第二foreach中使用&$a1
的引用传递
$array1 = [
['id'=> 1,'name'=>'John Sena', 'lastname'=>'Jonn'],
['id'=> 2,'name'=>'Rock', 'lastname'=>'Rock Sena']
];
$array2 = [
['id'=>1, 'company'=>'Warner Brother'], ['id'=>2, 'company'=>'Metro'],['id'=>'1', 'Address'=>'USA']
];
foreach ($array2 as $a2) {
foreach ($array1 as &$a1) {
if ($a2['id'] == $a1['id']) {
$a1 = array_merge($a1, $a2);
}
}
}
print_r($array1);
结果:
Array
(
[0] => Array
(
[id] => 1
[name] => John Sena
[lastname] => Jonn
[company] => Warner Brother
[Address] => USA
)
[1] => Array
(
[id] => 2
[name] => Rock
[lastname] => Rock Sena
[company] => Metro
)
)