tags:

views:

48

answers:

2

So basically I have these two arrays I want to merge...

array(1) { 
    ["first"]=>  
    array(1) { 
        ["second"]=>  
        array(0) { 
        } 
    } 
} 

array(1) { 
    ["second"]=>  
    array(1) { 
        ["third"]=>  
        array(0) { 
        } 
    } 
}

And this is the result I'd like to achieve...

array(1) { 
    ["first"]=>  
    array(1) { 
        ["second"]=>  
        array(1) {
            ["third"]=>  
            array(0) { 
            } 
        } 
    }  
}

But using $arr = array_merge_recursive($arr1, $arr2) I get this output:

array(2) { 
    ["first"]=>  
    array(1) { 
        ["second"]=>  
        array(0) { 
        } 
    } 
    ["second"]=>  
    array(1) { 
        ["third"]=>  
        array(0) { 
        } 
    } 
} 

From what I understand array_merge_recursive should get me what I want, but apparently doesn't. What would be a solution for my problem?

Thanks

A: 
$array2 = array('third' => array());
$array1['first']['second'] = $array2;
Gerrit
i think his actual data is way more complex.
antpaw
+1  A: 

The arrays are merged on the same 'levels'. Your arrays are not overlapping on the same level, one with a top-level value with 'first' and the other with 'second'. So it results in a new array with both arrays at top-level.

To achieve the result you want, you need to fill in

array_merge_recursive($arr1['first'], $arr2)

Then they match and will be combined equally to your expectations.

You could also write some function which recursively walks through your arrays finding the level where the arrays match and call the array_merge_recursive from there.

Veger
Yeah now I see what's wrong. Afraid your code snippet didn't help in my code but think I (almost) solved it in another way :)
per_pilot