dsbruqxgt820011351 2012-11-05 08:56
浏览 28
已采纳

PHP搜索数组

We have an array, for example:

$my_array = array('Software Engineering', 'Civil Engineering', 'Hardware Engineering', 'BL AH Engineering');

Now I have a "$q" variable, I want to search between values of the array, remove the keys which doesn't contain $q, here is my code:

foreach($my_array as $key => &$value){
    if (stripos(($value), $q) === false){
        unset($my_array[$key]);
    }
}

now if we set the $q = 'eer':

var_dump($my_array);
array
  0 => string 'Software Engineering' (length=20)
  1 => string 'Civil Engineering' (length=17)
  2 => string 'Hardware Engineering' (length=20)
  3 => &string 'BL AH Engineering' (length=17)

as you see, nothing is removed since all the $values have 'eer' in 'Engineering' it's OK, but now I set $q = 'eer civil', now:

var_dump($my_array);
array
  empty

all the items are removed, but actually the 'Civil Engineering' contains both the 'eer' and 'civil', so it should not be removed, how I could make this work? I may explode the $q with ' space ' but it's not working.

Thanks in advance

  • 写回答

5条回答 默认 最新

  • douju1997 2012-11-05 09:04
    关注

    Using explode should work:

    Update

    Use preg_split and trim to get rid of multiple/leading/trailing delimiters.

    $array = array('Software Engineering', 'Civil Engineering', 'Hardware Engineering', 'BL AH Engineering');
    $query = ' eer   civil ';
    $query = preg_split('/\s+/', trim($query));
    foreach ($array as $key => $value) {
        foreach ($query as $q) {
            if (stripos($value, $q) === false) {
                unset($array[$key]);
                break;
            }
        }
    }
    var_dump($array);
    

    http://codepad.org/r3jJX1aP

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程