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

时间:2021-06-24 12:31:41

I have to merge below two array but I am facing issue in coding it. Please help.

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

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


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

expected array is

预期的阵列是

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

1 个解决方案

#1


Like you can read in the comments you should use array_merge to build the sum of both arrays. And then use array_unique to replace the dublicate entries.

就像您可以在注释中阅读一样,您应该使用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>"; 

The output is:

输出是:

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

if you want to have clean indexes you can use array_values to reindex your array:

如果要使用干净的索引,可以使用array_values重新索引数组:

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

output:

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

#1


Like you can read in the comments you should use array_merge to build the sum of both arrays. And then use array_unique to replace the dublicate entries.

就像您可以在注释中阅读一样,您应该使用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>"; 

The output is:

输出是:

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

if you want to have clean indexes you can use array_values to reindex your array:

如果要使用干净的索引,可以使用array_values重新索引数组:

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

output:

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