Annan Annan - 5 months ago 8
PHP Question

How can I merge PHP arrays?

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?

Answer

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