Skip to content
Advertisement

Merge multi dimensional array preserving keys not working

I have following two arrays

$array1 = array (
  'MB04' => 
  array (
    78 => 
    array (
      2 => '30',
      1 => '30',
    ),
  ),
);

$array2 = array (
  'MB04' => 
  array (
    78 => 
    array (
      3 => '25',
    ),
  ),
);

I want to merge two arrays so that the final array looks like

$finalArray = array (
  'MB04' => 
  array (
    78 => 
    array (
      2 => '30',
      1 => '30',
      3 => '25'
    ),
  ),
);

I have used the following approaches but it’s not working:

# Approach 1
var_dump(array_merge($array1, $array2));

# Approach 2
var_dump($array1 + $array2);

# Approach 3
var_dump(array_merge_recursive($array1, $array2));

I want to achieve the final array with the native function (minimal code) if possible.

Advertisement

Answer

Finally found the solution using array_replace_recursive

# Approach 4
var_dump(array_replace_recursive($array1, $array2));

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement