How to combine multidimensional arrays while saving keys?

Is there any way for these arrays

$array1 = array( '21-24' => array( '1' => array("...") ) ); $array2 = array( '21-24' => array( '7' => array("..."), ) ); $array3 = array( '25 and over' => array( '1' => array("...") ) ); $array4 = array( '25 and over' => array( '7' => array("...") ) ); 

which will be combined into an array below?

 array( '21-24' => array( '1' => array("..."), '7' => array("...") ), '25 and over' => array( '1' => array("..."), '7' => array("...") ) ); 

Note

  • I have no control over the structure of the array, so any solution requiring a change in structure is not what I am looking for.
  • I am mainly interested in saving the keys of the first two levels, but a more reliable solution is a solution that can handle all levels.

I tried using array_merge_recursive () , like this

 $x = array_merge_recursive($array1, $array2); $x = array_merge_recursive($x, $array3); $x = array_merge_recursive($x, $array4); 

but it led to

  array( '21-24' => array( '1' => array("..."), '2' => array("...") ), '25 and over' => array( '1' => array("..."), '2' => array("...") ) ); 
+8
arrays php array-merge
source share
1 answer

Did you array_replace_recursive() ?

 print_r(array_replace_recursive($array1, $array2, $array3, $array4)); 
+21
source share

All Articles