是否可以像在
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
如果我只搜索它,它应该返回那些包含例如:
‘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
原文链接:https://www.f2er.com/php/133187.htmlpreg_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);
上面的代码首先在键中搜索lv(不区分大小写),然后在值中搜索,然后将结果合并到1个数组中.因此,结果是:
[jhon@test.lv.com] => John jack lv [bobby@test.lv.com] => Bob Mark [mark@test.by.com] => Mark Mian lv