如何在PHP数组中搜索,类似于MySQL Like%var%search

前端之家收集整理的这篇文章主要介绍了如何在PHP数组中搜索,类似于MySQL Like%var%search前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以像在 MySQL中一样在 PHP数组中进行搜索.

例如:我有这个阵列

array(
  'mark@test.com'=> `Mark Mian`,'jhon@test.com'=> `John jack`,'logon@test.com'=> `Bob logon`,'Stela@test.com'=> `Stela Josh`,'json@test.com'=> `Json Josh`
  'bobby@test.com'=> `Bob Mark`
)

我会做这种搜索,

例如:如果我搜索马克,它应该给我这个

‘mark@test.com’ => `Mark Mian

如果我搜索Bob,它应该归还给我

‘bobby@test.com’=> Bob Mark

logon@test.com’=> Bob logon,

如果我只搜索它,它应该返回那些包含例如:

‘mark@test.com’=> Mark Mian,

‘jhon@test.com’=> John jack,

‘Stela@test.com’=> Stela Josh,

‘bobby@test.com’=> Bob Mark

注意:搜索应该是键或值

这是一个preg_grep解决方案,应该更像MysqL中的WHERE REGEXP’PATTERN’.我修改Daniel Klein’s preg_grep_keys function搜索数组键中的模式,并添加了一个 array_merge,它应该与带有非数字键的数组一起使用.如果键是数字的,只需使用仅仅 preg_grep solution(preg_grep(‘~Mark~i’,$arr);来查找所有具有标记标记的数组元素等).

07001
Merges the elements of one or more arrays together so that the values of one are appended to the end of the prevIoUs one. It returns the resulting array.
If the input arrays have the same string keys,then the later value for that key will overwrite the prevIoUs one. If,however,the arrays contain numeric keys,the later value will not overwrite the original value,but will be appended.

function preg_grep_keys_values($pattern,$input,$flags = 0) {
    return array_merge(
      array_intersect_key($input,array_flip(preg_grep($pattern,array_keys($input),$flags))),preg_grep($pattern,$flags)
   );
}

$a = array(
  'mark@test.by.com'=> "Mark Mian lv",'jhon@test.lv.com'=> "John jack lv",'logon@test.en.com'=> "Bob logon",'Stela@test.es.com'=> "Stela Josh",'json@test.es.com'=> "Json Josh",'bobby@test.lv.com'=> "Bob Mark"
);

$r = preg_grep_keys_values('~lv~i',$a);
print_r($r);

this IDEONE demo

上面的代码首先在键中搜索lv(不区分大小写),然后在值中搜索,然后将结果合并到1个数组中.因此,结果是:

[jhon@test.lv.com] => John jack lv
[bobby@test.lv.com] => Bob Mark
[mark@test.by.com] => Mark Mian lv
原文链接:https://www.f2er.com/php/133187.html

猜你在找的PHP相关文章