加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 22:39:19 所属栏目:PHP教程 来源:网络整理
导读:是否可以像在 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'= `
是否可以像在 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读