PHP使用array_intersect()函數求數組交集


在PHP中求數組的交集,我們可以與PHP給我們提供的現成函數:array_intersect(),其用法格式為:

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

根據上述的語法格式,我們來寫一個例子:

<?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);
// 輸出結果:
// Array ( [0] => Apple )
?>

本例子將返回在$fruit1數組中出現且在$fruit2和$fruit3中也出現的所有水果的名子。

使用array_intersect()函數時要注意:只有在兩個元素相等且具有相同的數據類型時,array_intersect()函數才會認為它們是相同的,否則不能進行交集計算。array_intersect()函數返回一個保留了鍵的數組,只由第一個數組中出現的且在其它數組中都出現的值組成。

若要求關聯數組的交集,請使用array_intersect_assoc()函數,給你個簡單的例子:

<?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);
// 輸出:
// Array ( [red] => Apple )
?>

array_intersect_assoc()函數語法格式如下:

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM