PHP 中的集合运算

A∩B

array_intersect
example:

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

output

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

A-B & B-A

array_diff

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

output

Array
(
    [1] => blue
)

A∪B

array_unique
array_unique(array_merge($array1, $array2));
首先通过 array_merge 将两个数组进行合并,之后使用 array_unique 去掉数组中的重复项。

posted @ 2020-06-29 23:15  我听不见  阅读(342)  评论(0编辑  收藏  举报