简体   繁体   中英

Combine two multidimensional arrays

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" ).

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

Edit: Just seeing , a function exists for that :) : array_replace_recursive Docs . In case below PHP 5.3, this might still 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 invoking the function but in any case you need to specify the rules somehow. That's why array_merge_recursive saves each value.

Demo

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; 
} 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM