我需要的很简单:
我有两个这样的数组:
<?php
$a1 = [1,2,3];
$a2 = [2,3,4];
我需要将它们组合起来,结果是:
$result = [1,2,3,4];
我已尝试array_merge
,但结果为[1,2,3,2,3,4]
答案 0 :(得分:1)
您可以在此处找到答案:Set Theory Union of arrays in PHP
扩展您当前的方法。您可以在结果数组上调用array_unique
和sort
。
$a = [1,2,3];
$b = [2,3,4];
$result = array_merge($a, $b);
$result = array_unique($result);
sort($result);
这将导致:
array(4) {
[0] = int(1) 1
[1] = int(1) 2
[2] = int(1) 3
[3] = int(1) 4
}
答案 1 :(得分:0)
function merges(/*...*/){
$args=func_get_args();
$ret=array();
foreach($args as $arg){
foreach($arg as $key=>$v)
{
$ret[$key]=$v;
}
}
return $ret;
}
未经测试,但我想这可行..将删除所有重复的键并返回它找到的重复项的最后一个键/值对
答案 2 :(得分:0)
这可能就是你要找的东西
$result = $a1 + $a2 //union operation
实施例
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
输出
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}