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()基本相同,只不过他在比较中还考虑了数组的键。因此,只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才返回到结果数组中。

posted @ 2016-10-05 11:55  孤舟残月浅笑嫣然  阅读(8022)  评论(0编辑  收藏  举报