使用array_merge_recursive将数组合并在一起,但之后只将新内容添加到数组中?

使用array_merge_recursive将数组合并在一起,但之后只将新内容添加到数组中?

问题描述:

If you found the title misleading, sorry. I couldn't really come up with a good title for this question.

I have two arrays, that I'm merging together in a function:

$arr1['something']['secondary_something'][]="foo1";
$arr1['something']['secondary_something'][]="foo2";
$arr1['something']['secondary_something'][]="foo3";

$arr2['something']['secondary_something'][]="foo4";
$arr2['something']['secondary_something'][]="foo5";

function something($array_, $array_new) {

$array=array_merge_recursive($array_,$array_new); // to combine/merge both arrays

print_r($array);//debugg

}

Now that function simply prints this (which is all good):

Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo1 [1] => foo2 [2] => foo3 [3] => foo4 [4] => foo5 ) ) )

But I need to work with the new data, that has been merged to the primary array. So I need to work $arr2, but only once it has been merged with $arr1.

When I say I need to "work with the new data", var_export() is one of the things I need to do with the array.

If I simply do a echo var_export($array_new,true);, I get this:

array ( 'something' => array ( 'secondary_something' => array ( 0 => 'foo4', 1 => 'foo5', ), ), )

When I need this:

array ( 'something' => array ( 'secondary_something' => array ( 3 => 'foo4', 4 => 'foo5', ), ), )

^^ Notice how the array keys are 3 and 4, not 1 and 2. Because it has been merged with the primary array ($arr1).

Hope you guys understand what I'm trying to do.

Any ideas?

Thanks xD

echo var_export(array_intersect($array['something']['secondary_something'], $arr2['something']['secondary_something']), true);

EDIT This works, but you lose the multidimensional aspect of the array. You'll need to write a recursive function to step through the entire array if you want to preserve the something and secondary_something aspect in your var_export