试图将两个数组合并在一起

时间:2012-04-16 23:09:13

标签: php arrays array-merge

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

$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()函数的用途,这就是为什么它没有返回我希望它返回的结果。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分: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']);

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

答案 2 :(得分: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
}