首頁  >  文章  >  後端開發  >  php獲得數組交集與差集的方法是什麼

php獲得數組交集與差集的方法是什麼

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼原創
2019-08-28 16:09:422192瀏覽

php獲得數組交集與差集的方法是什麼

一、陣列的交集array_intersect()

array_intersect()函數傳回一個保留了鍵的陣列,這個數組只由第一個數組中出現的且在其他每個輸入數組中都出現的值組成。其形式如下:

array array_intersect(array array1,array array2[,arrayN…])

下面這個例子將返回在$fruit1數組中出現的且在$fruit2和$fruit3中也出現的所有的水果: 

<?php
$fruit1 = array("Apple","Banana","Orange");
$fruit2 = array("Pear","Apple","Grape");
$fruit3 = array("Watermelon","Orange","Apple");
$intersection = array_intersect($fruit1, $fruit2, $fruit3);
print_r($intersection);
// output
// Array ( [0] => Apple )
?>

只有在兩個元素相等且具有相同的資料類型時,array_intersect()函數才會認為它們是相同的。

相關推薦:《PHP教學

關聯陣列的交集array_intersect_assoc()

函數array_intersect_assoc()與array_intersect ()基本上相同,只不過他在比較中也考慮了數組的鍵。因此,只有在第一個陣列中出現,且在所有其他輸入陣列中也出現的鍵/值對才會回到結果陣列中。

形式如下:

array array_intersect_assoc(array array1,array array2[,arrayN…])

下面的範例回傳了出現在$fruit1陣列中,也同時出現在$fruit2與$fruit3中的所有鍵/值對:  

<?php
$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 )
?>

二、陣列的差集array_diff()

函數array_diff()傳回出現在第一個陣列中但其他輸入陣列中沒有的值。這個函數與array_intersect()相反。

array array_diff(array array1,array array2[,arrayN…])

實例如下: 

<?php
$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 )
?>

關聯陣列的差集array_diff_assoc()

函數array_diff_assoc()基本上與array_diff()相同,只是它在比較時也考慮了數組的鍵。因此,只在第一個陣列中出現而不再其他輸入陣列中出現的鍵/值對才會回到結果陣列中。其形式如下:

array array_diff_assoc(array array1,array array2[,arrayN…])

下面的範例只回傳了[yellow] => Banana,因為這個特殊的鍵/值對出現在$fruit1中,而在$fruit2和$fruit3中都不存在。

<?php
$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 )
?>

以上是php獲得數組交集與差集的方法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn