您的位置:首页 > 编程语言 > PHP开发

PHP使用array_intersect()函数求数组交集

2016-10-21 20:31 696 查看
在PHP中求数组的交集,我们可以与PHP给我们提供的现成函数:array_intersect(),其用法格式为:

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

根据上述的语法格式,我们来写一个例子:

1
<?php
2
$fruit1
=

array
(
"Apple"
,
"Banana"
,
"Orange"
);
3
$fruit2
=

array
(
"Pear"
,
"Apple"
,
"Grape"
);
4
$fruit3
=

array
(
"Watermelon"
,
"Orange"
,
"Apple"
);
5
$intersection

=
array_intersect
(
$fruit1
,
$fruit2
,
$fruit3
);
6
print_r(
$intersection
);
7
// 输出结果:
8
// Array ( [0] => Apple )
9
?>
本例子将返回在$fruit1数组中出现且在$fruit2和$fruit3中也出现的所有水果的名子。

使用array_intersect()函数时要注意:只有在两个元素相等且具有相同的数据类型时,array_intersect()函数才会认为它们是相同的,否则不能进行交集计算。array_intersect()函数返回一个保留了键的数组,只由第一个数组中出现的且在其它数组中都出现的值组成。

若要求关联数组的交集,请使用array_intersect_assoc()函数,给你个简单的例子:

1
<?php
2
$fruit1
=

array
(
"red"
=>
"Apple"
,
"yellow"
=>
"Banana"
,
"orange"
=>
"Orange"
);
3
$fruit2
=

array
(
"yellow"
=>
"Pear"
,
"red"
=>
"Apple"
,
"purple"
=>
"Grape"
);
4
$fruit3
=

array
(
"green"
=>
"Watermelon"
,
"orange"
=>
"Orange"
,
"red"
=>
"Apple"
);
5
$intersection

=
array_intersect_assoc
(
$fruit1
,
$fruit2
,
$fruit3
);
6
print_r(
$intersection
);
7
// 输出:
8
// Array ( [red] => Apple )
9
?>
array_intersect_assoc()函数语法格式如下:

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

 array_intersect_assoc()与array_intersect()基本相同,只不过他在比较中还考虑了数组的键。因此,只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才返回到结果数组中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php 函数
相关文章推荐