use*_*359 8 php recursion count
关于newb和我的Google-Fu的简单问题让我失望.使用PHP,如何计算给定目录中的文件数,包括任何子目录(以及它们可能具有的任何子目录等)?例如,如果目录结构如下所示:
/Dir_A/ /Dir_A/File1.blah /Dir_A/Dir_B/ /Dir_A/Dir_B/File2.blah /Dir_A/Dir_B/File3.blah /Dir_A/Dir_B/Dir_C/ /Dir_A/Dir_B/Dir_C/File4.blah /Dir_A/Dir_D/ /Dir_A/Dir_D/File5.blah
该脚本应返回"5"表示"./Dir_A".
我拼凑了以下但是它没有完全回答正确的答案,我不确定为什么:
function getFilecount( $path = '.', $filecount = 0, $total = 0 ){
$ignore = array( 'cgi-bin', '.', '..', '.DS_Store' );
$dh = @opendir( $path );
while( false !== ( $file = readdir( $dh ) ) ){
if( !in_array( $file, $ignore ) ){
if( is_dir( "$path/$file" ) ){
$filecount = count(glob( "$path/$file/" . "*"));
$total += $filecount;
echo $filecount; /* debugging */
echo " $total"; /* debugging */
echo " $path/$file
"; /* debugging */
getFilecount( "$path/$file", $filecount, $total);
}
}
}
return $total;
}
我非常感谢任何帮助.
Pao*_*ino 18
这应该做的伎俩:
function getFileCount($path) {
$size = 0;
$ignore = array('.','..','cgi-bin','.DS_Store');
$files = scandir($path);
foreach($files as $t) {
if(in_array($t, $ignore)) continue;
if (is_dir(rtrim($path, '/') . '/' . $t)) {
$size += getFileCount(rtrim($path, '/') . '/' . $t);
} else {
$size++;
}
}
return $size;
}
Run Code Online (Sandbox Code Playgroud)
And*_*ark 16
使用SPL,然后查看是否仍然出现错误.
用法示例:
<?php
$path = realpath('/etc');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
?>
Run Code Online (Sandbox Code Playgroud)
这将打印$ path下的所有文件和目录的列表(包括$ path ifself).如果要省略目录,请删除RecursiveIteratorIterator :: SELF_FIRST部分.
然后使用isDir()
根据安德鲁的回答...
$path = realpath('my-big/directory');
$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
$count=iterator_count($objects);
echo number_format($count); //680,642 wooohaah!
Run Code Online (Sandbox Code Playgroud)
这样我就可以计算(不列出)数千个文件。实际上在不到 4.6 秒的时间内处理了 680,642 个文件;)