今天在项目中,需要判断两个数组是否有交集,第一个感觉PHP中应该有这个函数,果然: array array_intersect(array array1,array array2[,arrayN…]) 返回N个数组中的交集元素,如果是关联数组可以用array_intersect_assoc() 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);
- // 输出 Array ( [0] => Apple )
- ?>
我的应用如下:
- if($user->role != 1){
- $count = count($projects);
- for($i=0;$i<$count;$i++){
- if(!array_intersect(explode(',', $projects[$i]['role']), explode(',', $projects[$i]['next_approve_role']))){
- unset($projects[$i]);
- continue;
- }
- }
- }
上面案例将数组中没有交集的元素从数组中剔除!
|