[英]How to search for a substring in array keys?
I have an array like below 我有一个像下面的数组
$array =array(
"123,456,789"=> "1,1,1",
"333"=>"1",
"777"=>"1"
)
Now if I am searching 456 then need to return me array key(123,456,789) and its value (1,1,1) 现在,如果我正在搜索456,那么需要返回数组键(123,456,789)及其值(1,1,1)
I also tried like below to make it working but i didn't get success.I need like if i am searching with any value of array key like (123 or 456 or 789) then need to provide me same result. 我也尝试下面的方法使它工作,但我没有成功。我需要,如果我正在搜索任何值的数组键,如(123或456或789),那么需要提供相同的结果。 I know that i can achieve this using foreach loop but i don't want to create foreach loop for this so suggest me if any other solution exists.
我知道我可以使用foreach循环实现这一点,但我不想为此创建foreach循环,所以建议我是否存在任何其他解决方案。
$matching_key = preg_grep("/\b456\b/", $array);
Sorry but I am not much good in regular expression. 对不起,但我在正则表达方面不太好。
Ideas? 想法? Any suggestions?
有什么建议?
preg_grep
function works on array's values , not keys as it is what you need. preg_grep
函数适用于数组的值 ,而不是键,因为它是您需要的。
You could get keys in first place. 你可以在第一时间得到钥匙。
<?php
$array =array(
"123,456,789"=> "1,1,1",
"333"=>"1",
"777"=>"1"
);
$keys = array_keys($array);
$matching_key = preg_grep("/\b456\b/", $keys);
var_dump($matching_key);
//returns "123,456,789"
https://3v4l.org/SndkV https://3v4l.org/SndkV
Anyway I need to say that you probably should change your data structure. 无论如何,我需要说你可能应该改变你的数据结构。 This looks like a bad design.
这看起来像一个糟糕的设计。
Here is a try 这是一个尝试
$array =array(
"123,456,789"=> "1,1,1",
"333"=>"1",
"777"=>"1"
);
$search = '456';
$result = [];
foreach($array as $key=>$value){
if (strpos($key, $search) !== false) {
array_push($result, $value);
}
}
Print_r($result);
$search
is a dynamic Variable which you want to search, i used str_pos()
, to find if the string is there in that key. $search
是一个动态变量,你想搜索,我使用str_pos()
来查找字符串是否在那个键中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.