对目录中的文件进行计数,但不包括子目录


Count files in directory, but exclude subdirectories

我发现了一篇旧帖子,其中有几乎完美的代码来解决我的问题:在一个目录中计算(许多)文件。它不包括。恩。。条目,但不包括其他目录。我通过添加评论添加了一个问题,但没有得到回复。(我想,这篇文章太老了)(计算php目录中的文件数量)

$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

在php.net上搜索过,但很多这个主题都没有文档记录。我确实发现了SKIP_DOTS的事实,但没有一封关于如何排除目录的信。

现在我的代码生成:有76849个文件但这也包括子目录。

如何更改此代码,以便排除我的子目录?

更新因为一些答案

/**
PHP version problem, need update first
$files = new FilesystemIterator('images');
$filter= new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
printf('There were %d Files', iterator_count($filter));
*/

$time0 = time();
$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);
$fileCount = 0;
foreach ($fi as $f) {
    if ($f->isFile()) {
        $fileCount++;
    }
}
printf("xThere were %d Files", $fileCount);
$time1 = time();
echo'<br />tijd 1 = '.($time1 - $time0); // outcome 5
echo'<hr />'; 

$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);
printf("yThere were %d Files", iterator_count($fi));
$time2 = time();
echo'<br />tijd 2 = '.($time2 - $time1); // outcome: 0

第一个答案我现在无法使用,因为我必须更新我的PHP版本。当测量时间时,第二个答案需要更多的时间来处理。

我还注意到,由于第二个答案,我自己的代码不计算子目录中的文件,它只计算子目录的数量,在我的情况下只有4个。因此,为了提高速度,我将使用我自己的代码并执行其中的第4行。下周我将尝试更新我的php版本,并将再次尝试。

感谢大家的贡献!!!

使用CallbackFilterIterators(自5.4起可用)很容易:

$files = new FilesystemIterator('images');
$filter= new CallbackFilterIterator($files, function($cur, $key, $iter) {
    return $cur->isFile();
});
printf('There were %d Files', iterator_count($filter));

假设文件有扩展名而目录没有扩展名,就容易多了:

$count = count(glob('images/*.*'));

或者过滤掉目录:

$count = count(array_diff(glob('images/*'), glob('images/*', GLOB_ONLYDIR)));

我会按如下方式进行:

$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);
$fileCount = 0;
foreach ($fi as $f) {
    if ($f->isFile()) {
        $fileCount++;
    }
}
printf("There were %d Files", $fileCount);

当你阅读它时,感觉就像是自我文档化的代码。

Symfony的"Finder"组件非常灵活,它通过直观流畅的界面(实际上它是许多SPL组件的包装器)查找文件和目录。几乎有30种方法可以配置结果。例如:大小、深度、排除、忽略文件、路径、排除、followLinks。。。。。。。。文件中的一个例子:

use Symfony'Component'Finder'Finder ;
$finder = new Finder();
$iterator = $finder
  ->files()
  ->name('*.php')
  ->depth(0)
  ->size('>= 1K')
  ->in(__DIR__);
foreach ($iterator as $file) {
    print $file->getRealpath()."'n";
}

"文件"组件甚至可以用于远程存储的文件(如亚马逊的S3)。安装很简单,只需将"symfony/finder":"2.3.*@dev"写入composer.json文件并运行"composer-update"CLI命令即可。截至目前,该组件已安装140万台,这是其质量的最佳证明。许多框架/项目在幕后使用此组件。

$fi=新的FilesystemIterator(DIR.'/images',FilesystemItator::SKIP_DOTS);printf("有%d个文件",迭代器计数($fi));