2013-05-16 60 views
2

我试图使用scandir()foreach()来获得匹配的文件数组。php - scandir和返回匹配的文件

当我运行scandir()然后它返回所有文件列表。它的okey在这里。

现在在第二步,当我做foreach scandir() s数组,然后我只得到一个匹配的文件。但有两个文件调用(请注意在做foreach之前我的scandir()返回包含这两个文件的所有文件);

widget_lc_todo.php 
widget_lc_notes.php 

的东西是在我的代码丢失,我不知道什么:-(

这里是我的代码:

$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); 
+3

您在找到第一个匹配的文件后立即调用'return'。 – Andrew

+0

我真是个大笨蛋,谢谢你,你是个石头 – user007

+0

有时候我们只需要在代码上加一双眼睛:) – Andrew

回答

2

你上面的代码,一旦调用return,因为它找到的第一个匹配文件,这意味着只要preg_match返回true就退出foreach循环,直到foreach循环退出后才能返回:

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