Question

I have two arrays of animals (for example).

$array = array(
    array(
        'id' => 1,
        'name' => 'Cat',
    ),
    array(
        'id' => 2,
        'name' => 'Mouse',
    )
);

$array2 = array(
    array(
        'id' => 2,
        'age' => 321,
    ),
    array(
        'id' => 1,
        'age' => 123,
    )
);

How can I merge the two arrays into one by the ID?

Was it helpful?

Solution

This does what Erik suggested (id no. as array key) and merges vlaues in $array2 to $results.

$results = array();

foreach($array as $subarray)
{
    $results[$subarray['id']] = array('name' => $subarray['name']);
}

foreach($array2 as $subarray)
{
    if(array_key_exists($subarray['id'], $results))
    {
        // Loop through $subarray would go here if you have extra 
        $results[$subarray['id']]['age'] = $subarray['age'];
    }
}

OTHER TIPS

@Andy

http://se.php.net/array_merge

That was my first thought but it doesn't quite work - however array_merge_recursive might work - too lazy to check right now.

First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)?

$array = array(
    1 => array(
        'name' => 'Cat',
    ),
    2 => array(
        'name' => 'Mouse',
    )
);

after that you'll have to foreach through one array, performing array_merge on the items of the other:

foreach($array2 as $key=>$value) {
  if(!is_array($array[$key])) $array[$key] = $value;
  else $array[$key] = array_merge($array[key], $value); 
}

Something like that at least. Perhaps there's a better solution?

<?php
      $a = array('a' => '1', 'b' => array('t' => '4', 'g' => array('e' => '8')));
      $b = array('c' => '3', 'b' => array('0' => '4', 'g' => array('h' => '5', 'v' => '9')));
      $c = array_merge_recursive($a, $b);
      print_r($c);
?>

array_merge_recursive — Merge two or more arrays recursively

outputs:

        Array
(
    [a] => 1
    [b] => Array
        (
            [t] => 4
            [g] => Array
                (
                    [e] => 8
                    [h] => 5
                    [v] => 9
                )

            [0] => 4
        )

    [c] => 3
)

@Andy

I've already looked at that and didn't see how it can help merge multidimensional arrays. Maybe you could give an example.

@kevin

That is probably what I will need to do as I think the code below will be very slow. The actual code is a bit different because I'm using ADOdb (and ODBC for the other query) but I'll make it work and post my own answer.

This works, however I think it will be very slow as it goes through the second loop every time:

foreach($array as &$animal)
{
    foreach($array2 as $animal2)
    {
        if($animal['id'] === $animal2['id'])
        {
            $animal = array_merge($animal, $animal2);
            break;
        }
    }
}
foreach ($array as $a)
    $new_array[$a['id']]['name'] = $a['name'];

foreach ($array2 as $a)
    $new_array[$a['id']]['age'] = $a['age'];

and this is result:

    [1] => Array
        (
            [name] => Cat
            [age] => 123
        )

    [2] => Array
        (
            [name] => Mouse
            [age] => 321
        )
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

With PHP 5.3 you can do this sort of merge with array_replace_recursive()

http://www.php.net/manual/en/function.array-replace-recursive.php

You're resultant array should look like:

Array (
    [0] => Array
        (
            [id] => 2
            [name] => Cat
            [age] => 321
        )

    [1] => Array
        (
            [id] => 1
            [name] => Mouse
            [age] => 123
        )
)

Which is what I think you wanted as a result.

I would rather prefer array_splice over array_merge because of its performance issues, my solution would be:

<?php 
array_splice($array1,count($array1),0,$array2);
?>
$new = array();
foreach ($array as $arr) {
    $match = false;
    foreach ($array2 as $arr2) {
        if ($arr['id'] == $arr2['id']) {
           $match = true;
           $new[] = array_merge($arr, $arr2);
           break;
        }
    }
    if ( !$match ) $new[] = $arr;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top