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

这篇博客介绍了如何使用preg_grep_keys_values函数在PHP中同时搜索数组键和值,实现类似MySQL WHERE REGEXP 功能。通过示例代码展示了如何查找包含特定模式的数组元素,并将结果合并到一个数组中。该函数适用于包含非数字键的数组,对于只有数字键的数组,可以直接使用preg_grep。示例中,函数在键和值中搜索'lv',最后输出包含匹配项的数组。
摘要由CSDN通过智能技术生成

这是一个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);

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

[jhon@test.lv.com] => John jack lv

[bobby@test.lv.com] => Bob Mark

[mark@test.by.com] => Mark Mian lv

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值