【问题标题】:How to find array key which has value containing certain string如何找到具有包含特定字符串的值的数组键
【发布时间】:2017-09-11 08:53:08
【问题描述】:

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

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

【问题讨论】:

  • 您可以使用 array_keys 生成数组键的数组并对其进行搜索,然后使用匹配的键从原始数组中检索它们的值。
  • 看看here
  • @Michel 我已经得到它搜索值,我想要它基于key
  • 从 PHP 5.6 开始,如果你将ARRAY_FILTER_USE_BOTH 作为array_filter() 的第三个参数传递,它会将值和键同时传递给回调函数。

标签: php arrays array-filter


【解决方案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);

【讨论】:

  • 感谢您的示例,很容易调整我的代码以使用与此类似的代码
  • @ChrisBeckett 很高兴帮助你的朋友.. :)
【解决方案2】:

您可以使用函数 array_keys 只获取数组 $example 的键

$matches = array_filter(array_keys($example), function($var) use ($searchword) { 
return preg_match("/\b$searchword\b/i", $var); });

【讨论】:

  • 调用未定义函数array_key()
猜你喜欢
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
  • 2017-05-01
  • 2012-10-14
  • 2014-06-07
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多