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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 :)
1
$array2 = array('third' => array());
$array1['first']['second'] = $array2;

1 Comment

i think his actual data is way more complex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.