phparraysmultidimensional-arraymappingmerging-data

Append a new associative element (with values drawn from a flat lookup array) to all rows of a 2d array


I need a help with merging two arrays. Let's say I have following arrays:

Array
(
[3] => Array
    (
        [id] => 3
        [name] => Lorem
        [type] => pl
    )

[2] => Array
    (
        [id] => 2
        [name] => Ipsum
        [type] => pl
    )

)

And the second one:

Array
(
    [6] => Sit dolor
    [4] => nostrud exercitation ullamco
    [3] => uuntur magni dolores
    [2] => corporis suscipit laboriosam
    [7] =>  quia non numquam eius modi tempora
 )

And desired output is:

Array
(
[3] => Array
    (
        [id] => 3
        [name] => Lorem
        [type] => pl
        [new_key] => uuntur magni dolores
    )

[2] => Array
    (
        [id] => 2
        [name] => Ipsum
        [type] => pl
        [new_key] => corporis suscipit laboriosam
    )
)

I have been trying to compare arrays with array_diff_key() method and then merge arrays in some loop, but I could't get it working. Is there any built in PHP function, or should I write my own?


Solution

  • You can simply iterate over first array:

    foreach ($arr1 as $key=> $item) {
        $arr1[$key]['new_key'] = isset($arr2[$item['id']]) ? $arr2[$item['id']] : '';
    }
    

    Or

    foreach ($arr1 as &$item) { //just for fun
        $item['new_key'] = isset($arr2[$item['id']]) ? $arr2[$item['id']] : '';
    }
    

    But it seems that your data comes from database. If I am right, you'd better use sql JOIN.