PHP数组 并集 交集 差集

并集

array_merge

字符串键名相同,后面覆盖前面,数字键名会在后面追加,不覆盖,参考代码如下

$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);

结果

Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )

如果键名都是数字的话,后面的数组元素会追加到前面数组之后,并重建索引

$array1 = array(1 => 2, 2 => 4, 3 => 6);
$array2 = array(1 => 1, 2 => 3, 3 => 5);
$result = array_merge($array1, $array2);
print_r($result);

结果

Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 1 [4] => 3 [5] => 5 )

使用+运算符

使用+运算符合并数组,会保留前面数组的键名,后面数组元素会追加到前面数组后面,并且键名相同时,是前面覆盖后面

$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
print_r($result);

结果

Array ( [0] => zero_a [2] => two_a [3] => three_a [1] => one_b [4] => four_b )

交集

array_intersect

第一个数组是主值,返回有相同元素的值(判断依据是元素字符串相同,即 (string) $elem1 === (string) $elem2),键值保留第一个元素的键值

$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);

结果

Array ( [a] => green [0] => red )

array_intersect_assoc

array_intersect_assoc不仅检查元素值,还会检查键名,都相同的元素才会保留下来,键值对 key => value 中的两个值仅在 (string) $elem1 === (string) $elem2 时被认为相等

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red", 100 => 'a100');
$array2 = array("a" => "green", "b" => "yellow", "blue", "red", '100' => 'a100');
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);

结果

Array ( [a] => green [100] => a100 )

差集

array_diff

返回前面数组有而后面没有的元素数组,保留前面元素的键名,相同判断是根据字符串值相同,即 (string) $elem1 === (string) $elem2

$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);

结果

Array ( [1] => blue )

array_diff_assoc

array_diff_assoc不仅检查元素,还检查键名,键值对 key => value 中的两个值仅在 (string) $elem1 === (string) $elem2 时被认为相等

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);

结果

Array ( [b] => brown [c] => blue [0] => red )

在来个例子

$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);

结果

Array ( [0] => 0 [1] => 1 )
posted @ 2020-08-26 10:32  whyly  阅读(5930)  评论(0编辑  收藏  举报