这是Hors答案的修改版,适用于我的情况,因为它会在传递时剥离掉基本目录,并且具有可以设置为false的递归开关,这也非常方便。此外,为了使输出更易读,我将文件和子目录文件分开,先添加文件,然后添加子目录文件(请参见结果)。 我尝试了一些其他方法和建议,最终得到了这个结果。我已经有另一种工作方法,非常相似,但似乎在没有文件的子目录中失败了,但该子目录有一个带有文件的子子目录,它不扫描子子目录以查找文件-因此有些答案可能需要测试这种情况。无论如何,我也想在这里张贴我的版本,以防有人在寻找...
function get_filelist_as_array($dir, $recursive = true, $basedir = '', $include_dirs = false) {
if ($dir == '') {return array();} else {$results = array(); $subresults = array();}
if (!is_dir($dir)) {$dir = dirname($dir);}
if ($basedir == '') {$basedir = realpath($dir).DIRECTORY_SEPARATOR;}
$files = scandir($dir);
foreach ($files as $key => $value){
if ( ($value != '.') && ($value != '..') ) {
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if (is_dir($path)) {
if ($include_dirs) {$subresults[] = str_replace($basedir, '', $path);}
if ($recursive) {
$subdirresults = get_filelist_as_array($path, $recursive, $basedir, $include_dirs);
$results = array_merge($results, $subdirresults);
}
} else {
$subresults[] = str_replace($basedir, '', $path);
}
}
}
if (count($subresults) > 0) {$results = array_merge($subresults, $results);}
return $results;
}
我认为在调用该函数时,需要注意的一件事情是不要将$basedir值传递给它...通常只需传递$dir(或现在也可以传递文件路径),并根据需要选择性地将$recursive设置为false。结果如下:
[0] => demo-image.png
[1] => filelist.php
[2] => tile.png
[3] => 2015\header.png
[4] => 2015\08\background.jpg
享受吧!好的,回到我实际使用这个程序的地方...
更新 添加了一个额外的参数来决定是否在文件列表中包含目录(记住需要传递其他参数才能使用此功能)。例如:
$results = get_filelist_as_array($dir, true, '', true);
RecursiveDirectoryIterator
- u_mulder