合并两个多维关联数组

时间:2013-04-25 23:31:03

标签: php arrays multidimensional-array array-merge

我有这两个数组,我想合并为一个数组,但很难搞清楚。请参阅下面的两段代码:

第一个阵列:

$propSelectMaxRow = max(array_keys($property_select_email));
$i = 0;
foreach($property_queue as $r) {
    if ($select_type == 3 || $select_type == 4 || $select_type == 5) {
        $i = $i + 1;
        $property_select_email[$propSelectMaxRow + $i] = $r;
    }
}

第二阵列:

$propSelectMaxRow = max(array_keys($property_select_email));
$i = 0;
foreach($property_select as $r) {
    if ($select_type == 1 || $select_type == 2 || $select_type == 4 || $select_type == 5) {
        $i = $i + 1;
        $property_select_email[$propSelectMaxRow + $i] = $r;
    }
}

编辑: 我希望最终的数组看起来像这样:

第一种数组格式:

Array ( 
    [1] => Array ( [code] => PPJ3 [street] => 34412 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 

    [2] => Array ( [code] => PLK3 [street] => 73517 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 

    [3] => Array ( [code] => HYK2 [street] => 55224 Fake Street [city] => Detroit [state] => MI [zip] => 48208 ) 
 )

第二种数组格式:

Array ( 
    [1] => Array ( [code] => JAK932 [street] => 353242 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 

    [2] => Array ( [code] => JA232 [street] => 7432 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 
 )   

最终的数组格式应为:

Array ( 
    [1] => Array ( [code] => PPJ3 [street] => 34412 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 

    [2] => Array ( [code] => PLK3 [street] => 73517 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 

    [3] => Array ( [code] => HYK2 [street] => 55224 Fake Street [city] => Detroit [state] => MI [zip] => 48208 ) 

    [4] => Array ( [code] => JAK932 [street] => 353242 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 

    [5] => Array ( [code] => JA232 [street] => 7432 Fake Street [city] => Detroit [state] => MI [zip] => 48223 ) 
 )

2 个答案:

答案 0 :(得分:1)

您可能需要像这样改进代码:

//$propSelectMaxRow = max(array_keys($property_select_email)); // no need
//$i = 0; //no need
foreach($property_queue as $r) {
    if ($select_type == 3 || $select_type == 4 || $select_type == 5) {
        //$i = $i + 1;
        $property_select_email[] = $r;
    }
}

同样,构建你的第二个数组。第二个循环将在第一个循环结束时附加数组(因此它们将自动合并)。

答案 1 :(得分:-1)

您似乎只需要使用array_merge