我需要获取指定目录中 JPG 文件的总数,包括其所有子目录。没有子子目录。
结构如下:
dir1/
2 files
subdir 1/
8 files
total dir1= 10 个文件
dir2/
5 files
subdir 1/
2 files
subdir 2/
8 files
total dir2= 15 个文件
我有这个函数,但它不能正常工作,因为它只计算最后一个子目录中的文件,并且总数是实际文件数量的 2 倍。(如果最后一个子目录中有 40 个文件,将输出 80)
public function count_files($path) {
global $file_count;
$file_count = 0;
$dir = opendir($path);
if (!$dir) return -1;
while ($file = readdir($dir)) :
if ($file == '.' || $file == '..') continue;
if (is_dir($path . $file)) :
$file_count += $this->count_files($path . "/" . $file);
else :
$file_count++;
endif;
endwhile;
closedir($dir);
return $file_count;
}
你可以这样做,使用递归目录迭代器
<?php
function scan_dir($path){
$ite=new RecursiveDirectoryIterator($path);
$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$filesize=$cur->getSize();
$bytestotal+=$filesize;
$nbfiles++;
$files[] = $filename;
}
$bytestotal=number_format($bytestotal);
return array('total_files'=>$nbfiles,'total_size'=>$bytestotal,'files'=>$files);
}
$files = scan_dir('./');
echo "Total: {$files['total_files']} files, {$files['total_size']} bytes\n";
//Total: 1195 files, 357,374,878 bytes
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)