如何使用相同的键将值从一个数组添加到另一个数组?

时间:2019-03-01 01:24:12

标签: php arrays

我有两个数组:

$arr1 = [
    [
        'id' => 1,
        'name' => 'John',
        'email' => 'j@mail.com'
    ],
    [
        'id' => 2,
        'name' => 'Jane',
        'email' => 'jane@mail.com'
    ]
];

第二个数组:

$arr2 = [
    [
        'id' => 1,
        'email' => 'john@yahoo.com'
    ],
    [
        'id' => 2,
        'email' => 'jane@yahoo.com'
    ],
    [
        'id' => 2,
        'email' => 'jane.doe@hotmail.com'
    ],
];

我想将所有具有相同“ id”的值从第二个数组添加到第一个数组。我期望的结果是:

$arr3 = [
    [
        'id' => 1,
        'name' => 'John',
        'email' => ['j@mail.com', 'john@yahoo.com']
    ],
    [
        'id' => 2,
        'name' => 'Jane',
        'email' => ['jane@mail.com', 'jane@yahoo.com', 'jane.doe@hotmail.com']
    ]
];

1 个答案:

答案 0 :(得分:1)

此代码将执行您想要的操作。它遍历$arr2的所有条目,在id中查找匹配的$arr1值,并在找到它们的位置,将$arr2中的电子邮件地址添加到电子邮件列表中$arr1中的值id

foreach ($arr2 as $arr) {
    if (($k = array_search($arr['id'], array_column($arr1, 'id'))) !== false) {
        if (is_array($arr1[$k]['email'])) {
            $arr1[$k]['email'][] = $arr['email'];
        }
        else {
            $arr1[$k]['email'] = array($arr1[$k]['email'], $arr['email']);
        }
    }
}

输出:

Array (
    [0] => Array (
        [id] => 1 
        [name] => John
        [email] => Array (
            [0] => j@mail.com
            [1] => john@yahoo.com
        )
    )
    [1] => Array (
        [id] => 2
        [name] => Jane
        [email] => Array (
            [0] => jane@mail.com
            [1] => jane@yahoo.com
            [2] => jane.doe@hotmail.com
        )
    )
)