Merging two multidimensional arrays on specific key

user1292810 picture user1292810 · Dec 2, 2012 · Viewed 12.3k times · Source

Let's say I have following arrays:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
            )

        [1] => Array
            (
                [id] => 4
                [name] => Computers
            )

        [3] => Array
            (
                [id] => 7
                [name] => Science

        [4] => Array
            (
                [id] => 1
                [name] => Sports
            )
    )

And the second one:

Array
    (
        [0] => Array
            (
                [id] => 1
                [title] => Sport
            )

        [1] => Array
            (
                [id] => 7
                [title] => Sci
            )

        [3] => Array
            (
                [id] => 4
                [title] => Comp

        [4] => Array
            (
                [id] => 5
                [title] => Edu
            )
    )

And desired output is:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
                [title] => Edu
            )

        [1] => Array
            (
                [id] => 4
                [name] => Computers
                [title] => Comp
            )

        [3] => Array
            (
                [id] => 7
                [name] => Science
                [title] => Sci

        [4] => Array
            (
                [id] => 1
                [name] => Sports
                [title] => Sport
            )
    )

I have managed to merge these arrays with simply:

foreach($first as $key => $value){
    $result[$key] = array_merge($first[$key], $second[$key]);
}

But the output is not combined correctly:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
                [title] => Sport
            )

        [1] => Array
            (
                [id] => 4
                [name] => Computers
                [title] => Sci
            )

        [3] => Array
            (
                [id] => 7
                [name] => Science
                [title] => Comp

        [4] => Array
            (
                [id] => 1
                [name] => Sports
                [title] => Edu
            )
    )

The problem is I would like to merge these arrays on the same id. Desired output sorting should be same as in the first array.

How can I achieve this? Any help is much appreciated.

Answer

WebChemist picture WebChemist · Dec 2, 2012

You can just do a nested loop and check if the id values match, then add title to $first (or name to $second)

foreach($first as $key => $value){
    foreach($second as $value2){
        if($value['id'] === $value2['id']){
            $first[$key]['title'] = $value2['title'];
        }               
    }
}