【问题标题】:PHP array keys function contains said valuePHP数组键函数包含所述值
【发布时间】:2014-05-29 04:58:18
【问题描述】:

我正在为特定值搜索一个数组,我想知道是否可以搜索以查看该值是否包含我正在搜索的内容,不一定是完全匹配

所以..

$a = array("red", "reddish", "re", "red diamond");

这只会给我一把钥匙

$red = array_keys($a, "red");

如果我想要所有包含红色单词的键怎么办。所以我想要“红色”、“红色”和“红色菱形”

或者更确切地说,我想要0, 1, 3

【问题讨论】:

  • foreach 循环然后使用 preg_match 或 substr 来比较前 3 个字母
  • @Jef - 这是一个相当远的延伸。虽然我看到了解决方案的相似之处,但问题却大不相同。
  • @SanuelJackson - 很公平。对我来说,这仍然是一个“如何使用子字符串搜索数组”的问题。无论如何,您的答案比链接的答案更详细。

标签: php


【解决方案1】:

你可以这样做 > Live Demonstration

专门搜索Red

// Create a function to filter anything 'red'
function red($var) {
  if(strpos($var, 'red') === false) {
      // If array item does not contain red, filter it out by returning false
      return false;
  } else {
      // If array item contains 'red', then keep the item
      return $var;
  }

}


// Set the array (as per your question)
$array = array("red", "reddish", "re", "red diamond");

// This line executes the function red() passing the array to it.    
$newarray = array_filter($array, 'red');

// Dump the results
var_export(  array_keys($newarray) );

使用array_filter()array_map() 使开发人员可以更好地控制通过数组的快速循环,以过滤和执行其他代码。上面的函数旨在满足您的要求,但它可以根据您的需要进行复杂的操作。

如果您希望将其中的值“红色”设置为更具动态性,您可以执行以下操作:

通用搜索方法

// Set the array (as per your question)
$array = array("red", "reddish", "re", "red diamond");

// Set the text you want to filter for    
$color_filter = 'red';

// This line executes the function red() passing the array to it.    
$newarray = array_filter($array, 'dofilter');

// Dump the results
var_export(  array_keys($newarray) );


// Create a function to filter anything 'red'
function dofilter($var) {
  global $color_filter;
  if(strpos($var, $color_filter) === false) {
      // If array item does not contain $color_filter (value), filter it out by returning false
      return false;
  } else {
      // If array item contains $color_filter (value), then keep the item
      return $var;
  }

}

【讨论】:

  • 我觉得应该是$newarray = array_filter($array, "red");
  • @SharanyaDutta - 是的,我只是在纠正你写的那个:)
  • 你希望它返回什么。当它坐下时,它返回 0,1,3 ...你希望它返回 'red', 'reddish','red diamond' 吗? .. 如果是这样,只需将var_export( array_keys($newarray) ); 更改为var_export( $newarray );
【解决方案2】:

使用preg_grep:

$a = array("red", "reddish", "re", "red diamond");
$red = array_keys(preg_grep("/red/", $a));
print_r($red);

DEMO

以上代码为您提供$a包含 字符串"red" 的所有值的键。如果您需要$a字符串"red" 开头的所有值的键,只需将正则表达式从"/red/" 更改为"/^red/"

【讨论】:

  • 我什至无法通过编译器。
  • 您使用的是什么版本的 PHP?函数 preg_grep 自 PHP 4.2.0 起可用。
【解决方案3】:
$a = array("red", "reddish", "re", "red diamond");

function find_matches( $search, $array )
{
    $keys = array();
    foreach( $array as  $key => $val )
    {
        if( strpos( $val, $search ) !== false )
            $keys[] = $key;
    }
    return $keys;
}

【讨论】:

    猜你喜欢
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多