php数组交集方法,PHP获得数组交集与差集的方法
本文實例講述了PHP獲得數(shù)組交集與差集的方法。分享給大家供大家參考。具體分析如下:
一、數(shù)組的交集 array_intersect()
array_intersect()函數(shù)返回一個保留了鍵的數(shù)組,這個數(shù)組只由第一個數(shù)組中出現(xiàn)的且在其他每個輸入數(shù)組中都出現(xiàn)的值組成。其形式如下:
array array_intersect(array array1,array array2[,arrayN…])
下面這個例子將返回在$fruit1數(shù)組中出現(xiàn)的且在$fruit2和$fruit3中也出現(xiàn)的所有的水果:
$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 )
?>
只有在兩個元素相等且具有相同的數(shù)據(jù)類型時,array_intersect()函數(shù)才會認為它們是相同的。
關聯(lián)數(shù)組的交集 array_intersect_assoc()
函數(shù)array_intersect_assoc()與array_intersect()基本相同,只不過他在比較中還考慮了數(shù)組的鍵。因此,只有在第一個數(shù)組中出現(xiàn),且在所有其他輸入數(shù)組中也出現(xiàn)的鍵/值對才返回到結(jié)果數(shù)組中。
形式如下:
array array_intersect_assoc(array array1,array array2[,arrayN…])
下面的例子返回了出現(xiàn)在$fruit1數(shù)組中,也同時出現(xiàn)在$fruit2與$fruit3中的所有鍵/值對:
$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 )
?>
二、數(shù)組的差集 array_diff()
函數(shù)array_diff()返回出現(xiàn)在第一個數(shù)組中但其他輸入數(shù)組中沒有的值。這個功能與array_intersect()相反。
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 )
?>
關聯(lián)數(shù)組的差集 array_diff_assoc()
函數(shù)array_diff_assoc()與array_diff()基本相同,只是它在比較時還考慮了數(shù)組的鍵。因此,只在第一個數(shù)組中出現(xiàn)而不再其他輸入數(shù)組中出現(xiàn)的鍵/值對才會返回到結(jié)果數(shù)組中。其形式如下:
array array_diff_assoc(array array1,array array2[,arrayN…])
下面的例子只返回了[yellow] => Banana,因為這個特殊的鍵/值對出現(xiàn)在$fruit1中,而在$fruit2和$fruit3中都不存在。
$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程序設計有所幫助。
總結(jié)
以上是生活随笔為你收集整理的php数组交集方法,PHP获得数组交集与差集的方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AI理论知识整理(12)-向量子空间
- 下一篇: AI理论知识整理(13)-标准基