PHP组合数组

时间:2010-10-15 10:16:46

标签: php arrays

如何组合这两个数组,如果有重复的数组只有一个使用PHP表示。

Array
(
    [0] => 18
    [1] => 20
    [2] => 28
    [3] => 29
)

Array
(
    [0] => 1
    [1] => 8
    [2] => 19
    [3] => 22
    [4] => 25
    [5] => 28
    [6] => 30
)

3 个答案:

答案 0 :(得分:10)

听起来你需要:

 array_unique(array_merge($first_array, $second_array));

答案 1 :(得分:3)

array_unique应用于array_merge函数的结果。

示例:

php > $f=array(1,2,3,4,5);
php > $r=array(4,5,6,7,8);
php > print_r(array_unique(array_merge($r,$f)));
Array
(
    [0] => 4
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 8
    [5] => 1
    [6] => 2
    [7] => 3
)

答案 2 :(得分:1)

只需使用sum运算符合并两个数组的值,例如:

$first = array(18, 20, 21, 28, 29);
$second = array(1, 8, 18, 19, 21, 22, 25, 28, 30); // Contains some elements of $first
$sum = $first + $second;

结果数组应包含两个数组的元素,然后您可以使用array_unique $result = array_unique($sum);过滤掉重复数据。此时,结果数组将包含两个数组的元素,但只包含一次:

Array
(
    [0] => 18
    [1] => 20
    [2] => 21
    [3] => 28
    [4] => 29
    [5] => 22
    [6] => 25
    [7] => 28
    [8] => 30
)