如何使用foreach引用从array2的匹配ID组合array1

时间:2018-07-25 15:49:31

标签: php arrays multidimensional-array

我有两个数组。 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']
];

2 个答案:

答案 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
        )

)

Demo