0

我有两个数组,我只是想在一个函数中合并在一起:

$var1=array();
$myInputVar=array();
$var1['something']['secondary_something'][]="foo1";
$var1['something']['secondary_something'][]="foo2";
$var1['something']['secondary_something'][]="foo3";

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

function something(&$array_, $array_new) {
   $array = array_merge($array_ , $array_new); 

    print_r($array);//for debugging

}   
something($var1, $myInputVar);

现在打印:

Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo1 [1] => foo2 [2] => foo3 ) ) )

当我期待:

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

我也试过:

$array = $array_ + $array_new;

仍然没有打印出我的期望。

我有一种感觉,我误解了array_merge()函数的目的,这就是为什么它没有返回我期望它返回的结果。

有任何想法吗?

4

3 回答 3

1

试试array_merge_recursive()

于 2012-04-16T23:13:12.460 回答
0

array_merge将从左到右工作。在你的情况下:

$array_['something']['secondary_something']

将被覆盖

$array_new['something']['secondary_something']

您可以执行以下操作:

function something(&$array_, $array_new) {
    $array = array_merge($array_ , $array_new); 
    return $array;
}

$var1['something']['secondary_something'] = something($var1['something']['secondary_something'], $myInputVar['something']['secondary_something']);

否则,您将需要创建一个知道关联键并将适当组合数组的函数。

于 2012-04-16T23:16:21.000 回答
0
function something(&$array_, $array_new) {
    foreach ($array_new as $val)
        foreach ($val as $val2)
            foreach ($val2 as $val3)
                array_push($array_['something']['secondary_something'], $val3);
    print_r($array_);//for debugging
}  
于 2012-04-16T23:27:33.267 回答