使用 PHP 递归计算文件 [英] Recursively counting files with PHP
本文介绍了使用 PHP 递归计算文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对新手的简单问题,而我的 Google-Fu 却让我失望.使用 PHP,您如何计算给定目录中的文件数量,包括任何子目录(以及它们可能拥有的任何子目录等)?例如如果目录结构如下所示:
<前>/目录_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".
我拼凑了以下内容,但没有完全返回正确答案,我不确定为什么:
<前>函数 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 " $path/$file";/* 调试 */getFilecount( "$path/$file", $filecount, $total);}}}返回 $total;}
非常感谢您的帮助.
解决方案
这应该可以解决问题:
function getFileCount($path) {$size = 0;$ignore = array('.','..','cgi-bin','.DS_Store');$files = scandir($path);foreach($files as $t) {if(in_array($t, $ignore)) 继续;if (is_dir(rtrim($path, '/') . '/' . $t)) {$size += getFileCount(rtrim($path, '/') . '/' . $t);} 别的 {$size++;}}返回 $size;}
Simple question for a newb and my Google-Fu is failing me. Using PHP, how can you count the number of files in a given directory, including any sub-directories (and any sub-directories they might have, etc.)? e.g. if directory structure looks like this:
/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
The script should return with '5' for "./Dir_A".
I've cobbled together the following but it's not quite returning the correct answer, and I'm not sure why:
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; }
I'd greatly appreciate any help.
解决方案
This should do the trick:
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 递归计算文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文