将两个数组合并为一个(追加)

时间:2014-03-14 16:03:45

标签: php arrays

如何在PHP中组合两个数组,如追加它们?我试过 array_merge 但是tis函数返回了我想要的其他东西。有例子:

阵列1样本

[test1] => Array
(
    [0] => one
    [1] => two
)

[test2] => Array
(
    [0] => three
    [1] => four
)

数组2样本

[test1] => Array
(
    [0] => five
    [1] => six
)

[test2] => Array
(
    [0] => seven
    [1] => eight
)

预期结果

[test1] => Array
(
    [0] => one
    [1] => two
    [2] => five
    [3] => six
)

[test2] => Array
(
    [0] => three
    [1] => four
    [2] => seven
    [3] => eight
)

2 个答案:

答案 0 :(得分:7)

您想要array_merge_recursive()

$arr1 = array(
    'test1' => array('one', 'two'),
    'test2' => array('three', 'four'),
);

$arr2 = array(
    'test1' => array(2 => 'five', 3 => 'six'),
    'test2' => array(2 => 'seven', 3 => 'eight'),
);

$new_array = array_merge_recursive($arr1, $arr2);
print_r($new_array);

答案 1 :(得分:3)

您需要使用array_merge_recursive代替array_merge

$new_array_merged = array_merge_recursive($array1, $array2);