PHP使用array_intersect()函数求数组交集
2016-10-21 20:31
696 查看
在PHP中求数组的交集,我们可以与PHP给我们提供的现成函数:array_intersect(),其用法格式为:
根据上述的语法格式,我们来写一个例子:
本例子将返回在$fruit1数组中出现且在$fruit2和$fruit3中也出现的所有水果的名子。
使用array_intersect()函数时要注意:只有在两个元素相等且具有相同的数据类型时,array_intersect()函数才会认为它们是相同的,否则不能进行交集计算。array_intersect()函数返回一个保留了键的数组,只由第一个数组中出现的且在其它数组中都出现的值组成。
若要求关联数组的交集,请使用array_intersect_assoc()函数,给你个简单的例子:
array_intersect_assoc()函数语法格式如下:
array_intersect_assoc()与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 | ?> |
使用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 array_intersect_assoc(array array1,array array2[,arrayN…])
array_intersect_assoc()与array_intersect()基本相同,只不过他在比较中还考虑了数组的键。因此,只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才返回到结果数组中。
相关文章推荐
- PHP使用array_intersect()函数求数组交集
- php-Arrays 函数-array_intersect_key-使用键名比较计算数组的交集
- PHP数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数的小问题
- PHP数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数的小问题
- php中的常用数组函数(三)(获取数组交集的函数们 array_intersect()、array_intersect_key()、array_intersect_assoc()、array_intersect_uassoc()、array_intersect_ukey())
- php-Arrays 函数-array_intersect-计算数组的交集
- PHP数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数详解
- PHP - Manual手册 - V. Array 数组函数 - array_intersect计算数组的交集
- PHP数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数详解
- php-Arrays 函数-array_intersect_ukey-用回调函数比较键名来计算数组的交集
- php数组函数序列之array_intersect() 返回两个或多个数组的交集数组
- php数组函数序列之array_intersect() 返回两个或多个数组的交集数组
- php-Arrays 函数-array_intersect_assoc-带索引检查计算数组的交集
- PHP数组的交集array_intersect(),array_intersect_assoc(),array_inter_key()函数的小问题
- PHP中使用函数array_merge()合并数组
- PHP学习笔记之array_intersect_key() 函数使用
- php数组合并array_merge()函数使用注意事项
- php数组合并array_merge()函数使用注意事项
- PHP数组处理函数的使用array_map(三)
- php数组函数序列 之shuffle()和array_rand() 随机函数使用介绍