【问题标题】:PHP array search within array数组内的PHP数组搜索
【发布时间】:2016-04-01 15:33:57
【问题描述】:
$keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');

$strings = array(
'She had a pink dress',
'I have a white chocolate',
'I have a green balloon',
'I have a chocolate shirt',
'He had a new yellow book',
'We have many blue boxes',
'I have a magenta tie');

实际上,strings 数组非常庞大(超过 50k 个条目)。

运行搜索和提取匹配字符串的最佳方法是什么?

【问题讨论】:

  • 如果数据来自数据库,您应该已经在那里过滤。否则你可以使用array_filter()
  • @Shafizadeh 反过来,需要检查每个字符串中是否存在任何关键字。
  • 在每个字符串中,你的意思是?否则你的小例子已经没有结果了。
  • @GolezTrol 如果字符串包含 keywords 数组中的任何单词,则条件为真。
  • @jeroen 我现在正在研究array_filter。 :)

标签: php arrays string-matching


【解决方案1】:

使用array_filter 过滤$strings 数组。
将字符串拆分为一个数组,然后修剪每个单词,并使用array_intersect 检查单词数组是否包含任何$keywords

$result = array_filter($strings, function($val) use ($keywords) {
    return array_intersect( array_map('trim', explode(' ', $val)) , $keywords);
});

【讨论】:

  • 我宁愿在你的 lambda 函数中使用 use 语句而不是 global 关键字。
  • @flec - 我真的不喜欢use,但由于关键字可能不会改变,这里应该没有任何问题,所以我同意并编辑。
【解决方案2】:

最好的方法是使用array_filter()

$filtered_array = array_filter($strings,'filter');

function filter($a)
{
    $keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');

    foreach ($keywords as $k)
    {
        if (stripos($a,$k) !== FALSE)
        {
            return TRUE;
        }
    }

    return FALSE;
}

【讨论】:

  • 不知道您实际上可以将数组传递给stripos
  • 如果这个或任何答案解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
  • 你不能,它会抛出stripos(): needle is not a string or an integer
  • @adeneo 通过循环避免了这个问题。不是最优雅的解决方案,但它确实有效。
  • 出于性能原因,我将在您的过滤器函数之外定义 $keywords 并将其包含在 use 语句中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多