Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two multidimensional arrays

Tags:

arrays

php

I have two multidimensional arrays like:

[a]
  [b]
    [c]             

and

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

and want to turn it into a single array

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

I tried the array_merge_recursive() function, but it creates new elements on the last level instead of overwriting 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").

like image 474
Alex Avatar asked Oct 11 '11 19:10

Alex


2 Answers

Is this what you're after, 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

like image 91
Daren Chandisingh Avatar answered Oct 02 '22 07:10

Daren Chandisingh


Considering two arrays:

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

while using overwrite merge you would expect the result to be an array:

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

However most of the functions will result with this array:

So, here's a function to do that:

<?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; 
} 
?>
like image 34
Siva Charan Avatar answered Oct 02 '22 07:10

Siva Charan