合并具有相同索引的两个数组时出现问题

时间:2015-05-07 19:17:14

标签: php

我必须合并以下两个数组,但我在编码时面临问题。请帮忙。

array1 = array (
    [0] =>  "test",
    [1] =>  "test1",
    [2] =>  "test2" 
);


array2 = array(
    [0] => "test2",
    [1] => "test",
    [2] => "test1",
    [3] =>  "test3"         
)

预期的数组是

array(
    [0] => "test",
    [1] =>  "test1",
    [2] =>  "test2",
    [3] =>  "test3" 
)

1 个答案:

答案 0 :(得分:0)

就像您可以在评论中看到的那样,您应该使用array_merge来构建两个数组的总和。然后使用array_unique替换dublicate条目。

$array1 = array (
    0 =>  "test",
    1 =>  "test1",
    2 =>  "test2" 
);

$array2 = array(
    0 => "test2",
    1 => "test",
    2 => "test1",
    3 =>  "test3"         
);

$out = array_unique(array_merge($array1, $array2));

echo "<pre>";
print_r($out);
echo "</pre>"; 

输出结果为:

Array
(
    [0] => test
    [1] => test1
    [2] => test2
    [6] => test3
)

如果您想拥有干净的索引,可以使用array_values重新索引数组:

$out = array_values(array_unique(array_merge($array1, $array2)));

输出:

Array
(
    [0] => test
    [1] => test1
    [2] => test2
    [3] => test3
)