<?php
$arr1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three'
);$arr2 = array(
'2' => 'two',
'three' => 'three',
'4' => 'four',
'5' => 'five'
);//差集【對比返回在 arr1 中但是不在 arr2 及任何其它引數陣列中的值。】
$array_diff = array_diff($arr1,$arr2);
echo ""; print_r($array_diff);
/* 輸出結果
*array
*(* [0] => zero
* [1] => one
*)*/
array_diff_assoc() 函式用於比較兩個(或更多個)陣列的鍵名和鍵值 ,並返回差集。
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"red","b"=>"green","c"=>"blue");
$result=array_diff_assoc($a1,$a2);
print_r($result);
//array ( [d] => yellow )
//交集【對比返回既在 arr1 中也在 arr2 陣列中的值。】
# 注意事項: 鍵值保留arr1陣列中的鍵值不變
$array_intersect = array_intersect($arr1,$arr2);
echo ""; print_r($array_intersect);
/* 輸出結果
*array
*(* [2] => two
* [3] => three
*)*/
//並集【將arr1陣列中的值附加在arr2陣列的後面。返回作為結果的陣列。 】
#注意事項:【如果輸入的陣列中有相同的字串鍵名,則該鍵名後面的值將覆蓋前乙個值。
#然而,如果陣列包含數字鍵名,後面的值將不會覆蓋原來的值,而是附加到後面。】
$array_merge = array_merge($arr1,$arr2);
echo ""; print_r($array_merge);
/* 輸出結果
* array
* (* [0] => zero
* [1] => one
* [2] => two
* [3] => three
* [4] => two
* [three] => three
* [5] => four
* [6] => five
* )*/
?>
<?php
//交集【對比返回既在 arr1 中也在 arr2 陣列中的值。】
$a1="201801241730089114,201801250945342643,201801251354021259";
$a2="201712241027324612,201712251415274411,201801180033177196,201801221606284363,201801250945342643,201801251354021259";
$a11=explode(',', $a1);
$a12=explode(',', $a2);
print_r(array_intersect($a11,$a12));
echo (implode(",",array_intersect($a11,$a12)));
?>
PHP對陣列求交集,差集,並集示例
arr1 array 0 zero 1 one 2 two 3 three arr2 array 2 two three three 4 four 5 five 差集 對比返回在 arr1 中但是不在 arr2 及任何其它引數陣列中的值。array diff array diff arr1,arr2...
PHP 交集 並集 差集
array flip array splice 並集 array merge 過濾 array filter 去重 array unique 差集 array diff array diff 函式返回兩個陣列的差集陣列。該陣列包括了所有在被比較的陣列中,但是不在任何其他引數陣列中的鍵值。a1 arr...
JS陣列求並集,交集和差集
es7 filter結合includes 並集 let union a.concat b.filter v a.includes v 1,2,3,4,5 交集 let intersection a.filter v b.includes v 2 差集 let difference a.concat ...