1、差集:
array_diff()函数用于返回在第一个数组中存在,但在其他数组中不存在的值。
$array1 = [1, 2, 3, 4, 5];
$array2 = [4, 5, 6, 7, 8];
$diff = array_diff($array1, $array2);
print_r($diff);
输出:Array ( [0] => 1 [1] => 2 [2] => 3 )
2. 并集:
使用array_merge()函数将两个数组合并,然后使用array_unique()函数去除重复的值。
$array1 = [1, 2, 3, 4, 5];
$array2 = [4, 5, 6, 7, 8];
$union = array_merge($array1, $array2);
$union = array_unique($union);
print_r($union);
输出:Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )
3. 交集:
array_intersect()函数用于返回两个或更多数组中都存在的值。
$array1 = [1, 2, 3, 4, 5];
$array2 = [4, 5, 6, 7, 8];
$intersection = array_intersect($array1, $array2);
print_r($intersection);
输出:Array ( [3] => 4 [4] => 5 )
文章评论