是的:今天我很懒惰,在 Google 上搜索了一个针对递归目录列表的千篇一律的解决方案,结果发现了这个。当我最终编写自己的函数时(至于为什么我什至花时间去谷歌这超出了我的能力——我似乎总是觉得有必要重新发明轮子,没有合适的理由)我倾向于分享我的看法关于这个。
虽然有支持和反对使用 RecursiveDirectoryIterator 的意见,但我将简单地发表我对一个简单的递归目录函数的看法,并避免参与 RecursiveDirectoryIterator 的政治。
这里是:
function recursiveDirectoryList( $root )
{
/*
* this next conditional isn't required for the code to function, but I
* did not want double directory separators in the resulting array values
* if a trailing directory separator was provided in the root path;
* this seemed an efficient manner to remedy said problem easily...
*/
if( substr( $root, -1 ) === DIRECTORY_SEPARATOR )
{
$root = substr( $root, 0, strlen( $root ) - 1 );
}
if( ! is_dir( $root ) ) return array();
$files = array();
$dir_handle = opendir( $root );
while( ( $entry = readdir( $dir_handle ) ) !== false )
{
if( $entry === '.' || $entry === '..' ) continue;
if( is_dir( $root . DIRECTORY_SEPARATOR . $entry ) )
{
$sub_files = recursiveDirectoryList(
$root .
DIRECTORY_SEPARATOR .
$entry .
DIRECTORY_SEPARATOR
);
$files = array_merge( $files, $sub_files );
}
else
{
$files[] = $root . DIRECTORY_SEPARATOR . $entry;
}
}
return (array) $files;
}
有了这个函数,获取文件数的答案很简单:
$dirpath = '/your/directory/path/goes/here/';
$files = recursiveDirectoryList( $dirpath );
$number_of_files = sizeof( $files );
但是,如果您不想要相应文件路径数组的开销 - 或者根本不需要它 - 则无需按照建议将计数传递给递归函数。
可以简单地修改我原来的函数来执行计数:
function recursiveDirectoryListC( $root )
{
$count = 0;
if( ! is_dir( $root ) ) return (int) $count;
$dir_handle = opendir( $root );
while( ( $entry = readdir( $dir_handle ) ) !== false )
{
if( $entry === '.' || $entry === '..' ) continue;
if( is_dir( $root . DIRECTORY_SEPARATOR . $entry ) )
{
$count += recursiveDirectoryListC(
$root .
DIRECTORY_SEPARATOR .
$entry .
DIRECTORY_SEPARATOR
);
}
else
{
$count++;
}
}
return (int) $count;
}
在这两个函数中,如果目录不可读或发生其他错误,opendir() 函数实际上应该包含在条件中。确保正确执行:
if( ( $dir_handle = opendir( $dir ) ) !== false )
{
/* perform directory read logic */
}
else
{
/* do something on failure */
}
希望这对某人有所帮助...