我有多个字符串数组,我试图找出一种有效的方法来遍历它们以进行匹配,如果找到匹配项,则离开循环。对于每个数组,我已经在使用循环来检查匹配项。应该有更好的方法来做到这一点,而不仅仅是在代码中为每个数组重复内部循环,但我不知道该怎么做。
这是我的代码。它只显示 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
}
有没有办法循环遍历数组,当我们第一次找到匹配时就离开循环并对匹配做一些事情?
元芳怎么了