递归计数文件与PHP [英] Recursively counting files with PHP
本文介绍了递归计数文件与PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单的问题为newb和我的谷歌傅是失败了我。使用PHP,如何计算给定目录中的文件数,包括任何子目录(以及它们可能有的任何子目录等)?例如如果目录结构如下所示:
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
脚本应该返回'5 'for./Dir_A。
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;
}
我非常感谢任何帮助。
推荐答案
这应该做的诀窍:
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屋!
查看全文