php-扫描并返回匹配的文件

php-扫描并返回匹配的文件,php,arrays,foreach,Php,Arrays,Foreach,我正在尝试使用scandir()和foreach()获取匹配的文件数组 当我运行scandir()时,它将返回所有文件列表。这里没问题 现在在第二步中,当我执行foreachscandir()s数组时,我只得到一个匹配的文件。但是调用了两个文件(请注意,在执行foreach之前,my scandir()将返回包括这两个文件在内的所有文件) 我的代码中缺少某些内容,我不知道是什么:-( 这是我的密码: $path = get_template_directory().'/templates'; $

我正在尝试使用
scandir()
foreach()
获取匹配的文件数组

当我运行
scandir()
时,它将返回所有文件列表。这里没问题

现在在第二步中,当我执行foreach
scandir()
s数组时,我只得到一个匹配的文件。但是调用了两个文件(请注意,在执行foreach之前,my scandir()将返回包括这两个文件在内的所有文件)

我的代码中缺少某些内容,我不知道是什么:-(

这是我的密码:

$path = get_template_directory().'/templates';
$files = scandir($path);
print_r($files);
$template = array();
foreach ($files as $file){      
    if(preg_match('/widget_lc?/', $file)):
         $template[] = $file;
         return $template;

    endif;
}
print_r($template);

上面的代码在找到第一个匹配文件后立即调用
return
,这意味着只要
preg\u match
返回true,foreach循环就会退出。在foreach循环退出之前,您不应返回:

// ...
foreach ($files as $file){      
    if(preg_match('/widget_lc?/', $file)) {
         $template[] = $file;
    }
}
return $template;
// ...

在找到第一个匹配的文件后,您立即呼叫
return
。我真是个大傻瓜,谢谢你。有时我们只需要多看一眼代码:)没错,我花了3个多小时才解决了这个问题,但你在一秒钟内就解决了。。谢谢dear@Andrew,将该评论作为答案,然后选择该答案。因此,这个问题并不是“悬而未决”。
// ...
foreach ($files as $file){      
    if(preg_match('/widget_lc?/', $file)) {
         $template[] = $file;
    }
}
return $template;
// ...