Combining two multidimensional arrays

I have two multidimensional arrays of type:

[a] [b] [c] 

and

 [a] [b] [c] [d] 

and want to turn it into one array

 [a] [b] [c] [d] 

I tried the array_merge_recursive() function, but created new elements at the last level instead of writing them.

For example, if [c] is "X" in the first array and "Y" in the second array, I get array("X", "Y") instead of the last value ( "Y" ).

+4
source share
3 answers

Is this what you need using array_replace_recursive ?

 <?php $arr1 = array ('a' => array ('b' => array ('c' => 'X'), 'd' => 'array_1_d')); $arr2 = array ('a' => array ('b' => array ('c' => 'Y', 'd' => 'Z')), 'e' => 'array_2_e'); $arr3 = array_replace_recursive ($arr1, $arr2); var_dump($arr3); 

Outputs:

 array(2) { ["a"]=> array(2) { ["b"]=> array(2) { ["c"]=> string(1) "Y" ["d"]=> string(1) "Z" } ["d"]=> string(9) "array_1_d" } ["e"]=> string(9) "array_2_e" } 

http://www.php.net/manual/en/function.array-replace-recursive.php

+9
source

Edit: Just to see if there is a function for this :: array_replace_recursive Docs . In the case below PHP 5.3, this may be useful:

Union of two arrays (with string keys), recursive:

 function array_union_recursive(Array $a, Array $b) { foreach($a as $k => &$v) { if (is_array($v) && isset($b[$k]) && is_array($b[$k])) { $v = array_union_recursive($a[$k], $b[$k]); } } $a += $b; return $a; } 

If you want to get the last value instead of the first, you need to swap $a and $b when you call the function, but in any case you need to somehow define the rules. Therefore array_merge_recursive saves each value.

Demo

+1
source

Given two arrays:

 <?php $test1 = array(array('a','b','c'), 'a', 'b'); $test2 = array(array('d','e'), 'c'); ?> 

when using merge rewrite, you expect the result to be an array:

 <?php $test3 = array(array('d','e'), 'c', 'b'); ?> 

However, most functions will work with this array:

So here is the function for this:

 <?php function array_merge_overwrite(array &$array1, array $array2 = NULL) { $flag = true; foreach (array_keys($array2) as $key) { if (isset($array2[$key]) && is_array($array2[$key])) { if (isset($array1[$key]) && is_array($array1[$key])) array_merge_overwrite($array1[$key], $array2[$key]); else $array1[$key] = $array2[$key]; $flag = false; } } if ($flag == true) $array1 = $array2; } ?> 
+1
source

All Articles