为了账号安全,请及时绑定邮箱和手机立即绑定

PHP:寻求有效的结构来循环遍历数组进行匹配

PHP:寻求有效的结构来循环遍历数组进行匹配

PHP
慕后森 2021-10-15 15:39:41
我有多个字符串数组,我试图找出一种有效的方法来遍历它们以进行匹配,如果找到匹配项,则离开循环。对于每个数组,我已经在使用循环来检查匹配项。应该有更好的方法来做到这一点,而不仅仅是在代码中为每个数组重复内部循环,但我不知道该怎么做。这是我的代码。它只显示 3 个数组,但我想最终将其扩展到更多数组,因此代码将变得越来越低效。    $query = $_Request['q'];//query from Internet    $arrayMovies = array("La Dolce Vita","East of Eden","North by Northwest");    $arrayDirectors = array("Fellini","Ray","Hitchcock");    $arrayActors = array("Giancarlo","James","Jimmy");    $match = "";    $type = "";    $phrases = $arrayMovies;    foreach($phrases as $phrase)    {      if(preg_match("/" . $phrase . "/i", $query))      {        $match = $phrase;        $type = "movie";      }    }    //repeat for next array    $phrases = $arrayDirectors;    foreach($phrases as $phrase)    {      if(preg_match("/" . $phrase . "/i", $query))      {        $match = $phrase;        $type = "director";      }    }    //repeat for next array    $phrases = $arrayActors;    foreach($phrases as $phrase)    {      if(preg_match("/" . $phrase . "/i", $query))      {        $match = $phrase;        $type = "actor";      }    }    if ($match!="") {      //DO SOMETHING    }有没有办法循环遍历数组,当我们第一次找到匹配时就离开循环并对匹配做一些事情?
查看完整描述

2 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

这里有两个例子。您可以使用函数提前返回,或者中断循环。请注意,这两种方法都会在第一次匹配后短路。


<?php


$arrayDirectors = array("Fellini","Ray","Hitchcock");

$arrayMovies    = array("La Dolce Vita","East of Eden","North by Northwest");


function keyword_search($keyword, $array) {

    foreach($array as $value)

        if (preg_match("/\b" . preg_quote($keyword) . "/i", $value))

            return true;

}


if(keyword_search('Hitch', $arrayDirectors))

    echo 'Search term found in directors.';

输出:


Search term found in directors.

要查找您获得匹配的集合:


<?php

foreach(['directors' => &$arrayDirectors, 'movies' => &$arrayMovies] as $collection => $v)

{

    if(keyword_search('eden', $v)) {

        $matched = $collection;

        break;

    }

}


echo $matched;

输出:


movies

我在您的正则表达式中添加了一个单词边界,否则很容易过早匹配/或过度匹配恕我直言。


但您可能想要匹配多个标题。在这种情况下,您可能想要过滤数组:


<?php

$arrayMovies = array("North to Alaska","East of Eden","North by Northwest","Westworld");


function keyword_filter($keyword, $array) {

    return array_filter($array, function($value) use ($keyword) {

        return preg_match("/\b" . preg_quote($keyword) . "/i", $value);

    });

}    


var_export(keyword_filter('north', $arrayMovies));

echo "\n";

var_export(keyword_filter('west', $arrayMovies));

输出:


array (

    0 => 'North to Alaska',

    2 => 'North by Northwest',

)

array (

    3 => 'Westworld',

)


查看完整回答
反对 回复 2021-10-15
  • 2 回答
  • 0 关注
  • 101 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信