phparraysmultidimensional-arrayarray-mergearray-replace

How to merge two multi dimensional arrays by key value in php?


I have two arrays

$arr1 = [
    ['month' => 1], 
    ['month' => 2], 
    ['month' => 3], 
    ['month' => 4]
];

$arr2 = [
    ['month' => 3, 'info' => 'Alpha'], 
    ['month' => 4, 'info' => 'Beta']
];

I have tried array_merge & array_merge_recursive both are not merging arrays as my expected.

Expected Merging:

$arr3 = [
    ['month' => 1], 
    ['month' => 2], 
    ['month' => 3, 'info' => 'Alpha'], 
    ['month' => 4, 'info' => 'Beta']
];

Actual with array_merge_recursive is:

$arr3 = array_merge_recursive($arr2, $arr1);

$arr3 = [
    ['month' => 3, 'info' => 'Alpha'], 
    ['month' => 4, 'info' => 'Beta']
    ['month' => 1], 
    ['month' => 2], 
    ['month' => 3], 
    ['month' => 4]
];

Solution

  • In this case, I walk the arrays and construct the desired output.

    $output = [];
    $allMerged = array_merge($arr1, $arr2);
    array_walk($allMerged, 
      function($item, $key) use (&$output) {
        print_r($item);
        if ( array_key_exists($item['month'], $output) ) {
            if ( isset($item['info']) ) {
                $output[$item['month']]['info'] = $item['info'];
            } else {
                $output[$item['month']] = $item;
            }
        } else {
            $output[$item['month']] = $item;
        }
    });
    print_r($output);