如何查找包含某些字符串的值的数组键

时间:2017-09-11 08:53:09

标签: php arrays array-filter

我知道当我在数组中寻找值时,我可以这样做。

$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); });

2 个答案:

答案 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_fliparray_keyspreg_grep

解决方案1:

Try this code snippet here

<?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的好推荐

Try this code snippet here

<?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);