如何合并这两个数组?

时间:2021-03-17 12:15:04

I want to merge those two arrays and get only the unique key values. Is there a php function for this? array_merge() doesn't work.

我想合并这两个数组,只获取唯一的键值。这有一个PHP功能吗? array_merge()不起作用。

Array
(
    [1] => 3
    [2] => 4
    [3] => 1


)

Array
(
    [1] => 3
    [2] => 1
    [3] => 2

)

RESULT ARRAY THAT I WANT

结果阵列我想要的

Array
(
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4

)

4 个解决方案

#1


4  

$values = array_unique(array_merge($array1, $array2));
sort($values);

This returns the unique values from array1 and array2 (as per your example).

这将返回array1和array2中的唯一值(根据您的示例)。

Try it here: http://codepad.org/CeZewRNT

在这里试试:http://codepad.org/CeZewRNT

See array_merge() and array_unique().

请参阅array_merge()和array_unique()。

#2


3  

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

#3


1  

Following peice of code gives exact what you wants but the question is do you really want the keys in the result are starting from 1 instead of 0? If you don't Arnaud his option is the best solution.

下面的代码提供了你想要的确切内容,但问题是你真的希望结果中的键从1开始而不是0吗?如果你不是Arnaud他的选择是最好的解决方案。

$array1 = array(
    1 => 3,
    2 => 4,
    3 => 1
);

$array2 =  array(
    1 => 3,
    2 => 1,
    3 => 2
);

$values = array_unique(array_merge($array1, $array2));
$keys = array_keys(array_fill_keys($values, ''));
$result = array_combine($keys, $values);
asort($result);

var_dump($result);

#4


0  

Try this:

尝试这个:

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

#1


4  

$values = array_unique(array_merge($array1, $array2));
sort($values);

This returns the unique values from array1 and array2 (as per your example).

这将返回array1和array2中的唯一值(根据您的示例)。

Try it here: http://codepad.org/CeZewRNT

在这里试试:http://codepad.org/CeZewRNT

See array_merge() and array_unique().

请参阅array_merge()和array_unique()。

#2


3  

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

#3


1  

Following peice of code gives exact what you wants but the question is do you really want the keys in the result are starting from 1 instead of 0? If you don't Arnaud his option is the best solution.

下面的代码提供了你想要的确切内容,但问题是你真的希望结果中的键从1开始而不是0吗?如果你不是Arnaud他的选择是最好的解决方案。

$array1 = array(
    1 => 3,
    2 => 4,
    3 => 1
);

$array2 =  array(
    1 => 3,
    2 => 1,
    3 => 2
);

$values = array_unique(array_merge($array1, $array2));
$keys = array_keys(array_fill_keys($values, ''));
$result = array_combine($keys, $values);
asort($result);

var_dump($result);

#4


0  

Try this:

尝试这个:

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