我知道当我在数组中寻找值时,我可以这样做。
$example = array('example','One more example','last example');
$searchword = 'last';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
但是我想做这样的事情但是这个例子:
$example = array( "first" => "bar", "second" => "foo", "last example" => "boo");
$searchword = 'last';
如何更改此选项以获取包含searchword
而非值?
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
答案 0 :(得分:1)
您可以使用函数array_keys,它只获取数组$ example
的键$matches = array_filter(array_keys($example), function($var) use ($searchword) {
return preg_match("/\b$searchword\b/i", $var); });
答案 1 :(得分:1)
你可以尝试这个。我们在这里使用array_flip
,array_keys
和preg_grep
解决方案1:
<?php
$searchword = 'last';
$example = array( "first" => "bar", "second" => "foo", "last example" => "boo");
$result=array_flip(preg_grep("/$searchword/",array_keys($example)));
print_r(array_intersect_key($example, $result));
解决方案2:(Since PHP 5.6
)@axiac的好推荐
<?php
ini_set('display_errors', 1);
$searchword = 'last';
$example = array( "first" => "bar", "second" => "foo", "last example" => "boo");
$example=array_filter($example,function($value,$key) use($searchword){
return strstr($key, $searchword);
},ARRAY_FILTER_USE_KEY);
print_r($example);