Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Merging arrays with common keys

I need to get two arrays to merge into one while keeping all the keys in place and listing the values in an array like in this example:

$array1 = array('car' => '3', 'bus' => '2');
$array2 = array('dog' => '1', 'car' => '2', 'bird' => '9');  

$merged = array(
    'car' => array('3','2'), 
    'bus' => array('2',null),
    'dog' => array(null,'1'),
    'bird' => (null,'9')
);
like image 998
Mohammad Avatar asked Nov 01 '10 19:11

Mohammad


People also ask

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

How do I merge two arrays together?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


2 Answers

function merge_common_keys(){
    $arr = func_get_args();
    $num = func_num_args();

    $keys = array();
    $i = 0;
    for ($i=0; $i<$num; ++$i){
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys = array_unique($keys);

    $merged = array();

    foreach ($keys as $key){
        $merged[$key] = array();
        for($i=0; $i<$num; ++$i){
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;
}

Usage:

$merged = merge_common_keys($array1,$array2);

PS. It can work with more than two arrays, just pass as many as you want as next arguments.

like image 113
dev-null-dweller Avatar answered Sep 19 '22 04:09

dev-null-dweller


Something like this? http://php.net/array_merge_recursive

like image 25
Logan Bailey Avatar answered Sep 20 '22 04:09

Logan Bailey