Search code examples
phparraysmultidimensional-arraymergegrouping

Merge 2d array into another 2d array based on a column and create a subarray from related data in another column


I have two arrays:

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

And the second array:

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

I would like to add all values with the same 'id' from the second array to the first array. The result I expect would be:

$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']
    ]
];

Solution

  • This code will do what you want. It goes through all the entries of $arr2, looking for matching id values in $arr1 and, where it finds them, adding the email address from $arr2 to the list of emails in $arr1 for that id value:

    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']);
            }
        }
    }
    

    Output:

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