您有个知识币

【退出】

php数组交集

php数组交集如何取呢?这里说的php数组交集是指在第一个数组中出现的且在其他每个输入数组中都出现的值组成。

php为php数组交集提供了很好用的三个方法:

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

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

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

以上三个方法都是得到php数组交集的方法,功能分别介绍如下:

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

array_intersect()函数返回一个保留了键的数组,这个数组只由第一个数组中出现的且在其他每个输入数组中都出现的值组成。其形式如下:

下面这个例子将返回在$fruit1数组中出现的且在$fruit2和$fruit3中也出现的所有的水果:

Php代码

<?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()函数才会认为它们是相同的。

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

函数array_intersect_assoc()与array_intersect()基本相同,只不过他在比较中还考虑了数组的键。因此,只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才返回到结果数组中。

下面的例子返回了出现在$fruit1数组中,也同时出现在$fruit2与$fruit3中的所有键/值对:

Php代码

<?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_intersect_key(array array1,array array2[,arrayN…])

函数array_intersect_key()函数使用键名比较计算数组的交集。仅有键名用于比较。

实例如下:

<?php

$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");

$a2=array(2=>"Bird",0=>"Cat",4=>"Fish");

print_r(array_intersect_key($a1,$a2));

?>

//Array ( [0] => Cat [2] => Horse ) 输出

本文固定链接: http://www.webzhishi.com/php_intersect_1/ | web知识网

【上一篇】
【下一篇】

php数组交集:等您坐沙发呢!

发表评论