猿问

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

我有多个字符串数组,我试图找出一种有效的方法来遍历它们以进行匹配,如果找到匹配项,则离开循环。对于每个数组,我已经在使用循环来检查匹配项。应该有更好的方法来做到这一点,而不仅仅是在代码中为每个数组重复内部循环,但我不知道该怎么做。


这是我的代码。它只显示 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

    }

有没有办法循环遍历数组,当我们第一次找到匹配时就离开循环并对匹配做一些事情?


慕后森
浏览 102回答 2
2回答

元芳怎么了

这里有两个例子。您可以使用函数提前返回,或者中断循环。请注意,这两种方法都会在第一次匹配后短路。<?php$arrayDirectors = array("Fellini","Ray","Hitchcock");$arrayMovies&nbsp; &nbsp; = array("La Dolce Vita","East of Eden","North by Northwest");function keyword_search($keyword, $array) {&nbsp; &nbsp; foreach($array as $value)&nbsp; &nbsp; &nbsp; &nbsp; if (preg_match("/\b" . preg_quote($keyword) . "/i", $value))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;}if(keyword_search('Hitch', $arrayDirectors))&nbsp; &nbsp; echo 'Search term found in directors.';输出:Search term found in directors.要查找您获得匹配的集合:<?phpforeach(['directors' => &$arrayDirectors, 'movies' => &$arrayMovies] as $collection => $v){&nbsp; &nbsp; if(keyword_search('eden', $v)) {&nbsp; &nbsp; &nbsp; &nbsp; $matched = $collection;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}echo $matched;输出:movies我在您的正则表达式中添加了一个单词边界,否则很容易过早匹配/或过度匹配恕我直言。但您可能想要匹配多个标题。在这种情况下,您可能想要过滤数组:<?php$arrayMovies = array("North to Alaska","East of Eden","North by Northwest","Westworld");function keyword_filter($keyword, $array) {&nbsp; &nbsp; return array_filter($array, function($value) use ($keyword) {&nbsp; &nbsp; &nbsp; &nbsp; return preg_match("/\b" . preg_quote($keyword) . "/i", $value);&nbsp; &nbsp; });}&nbsp; &nbsp;&nbsp;var_export(keyword_filter('north', $arrayMovies));echo "\n";var_export(keyword_filter('west', $arrayMovies));输出:array (&nbsp; &nbsp; 0 => 'North to Alaska',&nbsp; &nbsp; 2 => 'North by Northwest',)array (&nbsp; &nbsp; 3 => 'Westworld',)
随时随地看视频慕课网APP
我要回答