[英]How to merge these two arrays?
I want to merge those two arrays and get only the unique key values. 我想合并这两个数组,并仅获取唯一的键值。 Is there a php function for this? 有没有为此的PHP功能? array_merge() doesn't work. 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
)
$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()
。
$merged = array_unique(array_merge($array1, $array2));
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? 遵循下面的代码给出了您想要的确切内容,但问题是您是否真的希望结果中的键从1而不是0开始? If you don't Arnaud his option is the best solution. 如果您不选择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);
尝试这个:
$merged = array_unique(array_merge($array1, $array2));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.