gpt4 book ai didi

PHP计算目录和子目录函数中的文件总数

转载 作者:可可西里 更新时间:2023-11-01 13:41:47 24 4
gpt4 key购买 nike

我需要获取指定目录中 JPG 文件的总数,包括它的所有子目录。没有子子目录。

结构如下:

dir1/2 files     subdir 1/       8 files

total dir1 = 10 files

dir2/     5 files      subdir 1/         2 files      subdir 2/         8 files

total dir2 = 15 files

I have this function, which doesn't work fine as it only counts files in the last subdirectory, and total is 2x more than the actual amount of files. (will output 80 if I have 40 files in the last subdir)

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;
}

最佳答案

您可以使用 RecursiveDirectoryIterator 这样做

<?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
?>

关于PHP计算目录和子目录函数中的文件总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10895343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com