gpt4 book ai didi

php - 使用 PHP 递归计数文件

转载 作者:可可西里 更新时间:2023-11-01 12:23:28 24 4
gpt4 key购买 nike

一个新手的简单问题,我的 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

对于“./Dir_A”,脚本应该返回“5”。

我拼凑了以下内容,但并没有返回正确的答案,我不确定为什么:

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

如果有任何帮助,我将不胜感激。

最佳答案

这应该可以解决问题:

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

关于php - 使用 PHP 递归计数文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/640931/

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