求兩個數組的交集問題可以使用array_intersect(),array_inersect_assoc,array_intersect_key來實現,其中array_intersect()函數是求兩個數的交集,返回一個交集共有元素的數組(只是數組值得比較)、array_intersect_assoc()函數是將鍵值和值綁定,一起比較交集部分、array_intersect_key()函數是將兩個數組的鍵值進行比較,返回鍵值交集的數組。
但實際應用中也遇到了一些小問題,正如下:
實例:
<?PHP $array = array("red"=>"Red","green"=>"red4","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz1"=>"art","peak"=>158); $array1 = array("red"=>"Red2","greena"=>"red","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz"=>"art","peak"=>158); $num = array_intersect($array,$array1); print_r ($num); echo "<br />"; $num = array_intersect_assoc($array,$array1); print_r($num); echo "<br />"; $num = array_intersect_key($array,$array1); print_r ($num); ?>
運行結果:
Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [azzzz1] => art [peak] => 158 ) Array ( [Red15] => Red [7] => Level [Width] => Red [peak] => 158 ) Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [peak] => 158 )
總結:
1.array_intersect()函數進行的比較只有數組值的比較,而且存在如”Red“和”Red2“比較時會返回"Red",反之則不會返回"Red2";
2.array_intersect_assoc()函數是將數組的值與鍵值一起比較,而且不會存在array_intersect的情況,適用於較嚴格的比較;
3.array_intersect_key()函數適用於比較兩個數組鍵值的交集,返回的並不只有鍵值,而是鍵值和對應的數組值。