PHP 求解數組的交集或者差集

一、數組的交集 array_intersect()

1.1 array_intersect()
``````函數返回一個保留了鍵的數組，這個數組只由第一個數組中出現的且在其他每個輸入數組中都出現的值組成。
``````
其形式如下：
``````array array_intersect(array array1,array array2[,arrayN…])
``````
示例
``````\$fruit1 = array("Apple","Banana","Orange");
\$fruit2 = array("Pear","Apple","Grape");
\$fruit3 = array("Watermelon","Orange","Apple");
\$intersection = array_intersect(\$fruit1, \$fruit2, \$fruit3);
print_r(\$intersection);

// Array ( [0] => Apple )
``````

1.2 array_intersect_assoc()
``````函數array_intersect_assoc()與array_intersect()基本相同，只不過他在比較中還考慮了數組的鍵。

``````
形式如下：
``````array array_intersect_assoc(array array1,array array2[,arrayN…])
``````
示例:
``````\$fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
\$fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
\$fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
\$intersection = array_intersect_assoc(\$fruit1, \$fruit2, \$fruit3);
print_r(\$intersection);
// output
// Array ( [red] => Apple )
``````

二、數組的差集

2.1 array_diff()
``````函數array_diff()返回出現在第一個數組中但其他輸入數組中沒有的值。

``````
形式如下：
``````array array_diff(array array1,array array2[,arrayN…])
``````
示例:
``````\$fruit1 = array("Apple","Banana","Orange");
\$fruit2 = array("Pear","Apple","Grape");
\$fruit3 = array("Watermelon","Orange","Apple");
\$intersection = array_diff(\$fruit1, \$fruit2, \$fruit3);
print_r(\$intersection);
// output
// Array ( [1] => Banana )
``````
2.2 array_diff_assoc()
``````函數array_diff_assoc()與array_diff()基本相同，只是它在比較時還考慮了數組的鍵。

``````
其形式如下：
``````array array_diff_assoc(array array1,array array2[,arrayN…])
``````
示例:
``````\$fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
\$fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
\$fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
\$intersection = array_diff_assoc(\$fruit1, \$fruit2, \$fruit3);
print_r(\$intersection);
// output
// Array ( [yellow] => Banana )
``````