9

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 = [
    'car' => '3',
    'bus' => '2'
];
$array2 = [
    'dog' => '1',
    'car' => '2',
    'bird' => '9'
];  

Desired result:

$merged = [
    'car' =>  ['3',  '2'], 
    'bus' =>  ['2',  null],
    'dog' =>  [null, '1'],
    'bird' => [null, '9']
];

3 Answers 3

14
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

this will not produce array with null value if key is present only in one array, bu only string with value from second array.
0

Populate a single array of your input arrays, then count the number of arrays to determine how many columns should have default values of null.

Before looping declare a flat array of null-defaulted values for all columns.

Then use nested loops to establish default elements for each newly encountered second level key and then swap the first and second level keys when pushing values into each group. Demo

$arrays = [
    ['car' => '3', 'bus' => '2'],
    ['dog' => '1', 'car' => '2', 'bird' => '9'],  
];

$defaults = array_fill(0, count($arrays), null);
$result = [];
foreach ($arrays as $i => $array) {
    foreach ($array as $k => $v) {
        $result[$k] ??= $defaults;
        $result[$k][$i] = $v;
    }
}
var_export($result);

Output:

array (
  'car' => 
  array (
    0 => '3',
    1 => '2',
  ),
  'bus' => 
  array (
    0 => '2',
    1 => NULL,
  ),
  'dog' => 
  array (
    0 => NULL,
    1 => '1',
  ),
  'bird' => 
  array (
    0 => NULL,
    1 => '9',
  ),
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.