使用PHP返回文件夹中的文件总数

PHL*_*LAK 12 php directory file count

是否有更好/更简单的方法来查找目录中的图像数量并将它们输出到变量?

function dirCount($dir) {
  $x = 0;
  while (($file = readdir($dir)) !== false) {
    if (isImage($file)) {$x = $x + 1}
  }
  return $x;
}
Run Code Online (Sandbox Code Playgroud)

这似乎是这么长的一种方式,有没有更简单的方法?

注意:如果文件是图像,则isImage()函数返回true.

bbx*_*bby 25

查看DirectoryIterator的标准PHP库(aka SPL):

$dir = new DirectoryIterator('/path/to/dir');
foreach($dir as $file ){
  $x += (isImage($file)) ? 1 : 0;
}
Run Code Online (Sandbox Code Playgroud)

(仅供参考,有一个名为iterator_count()的未记录函数,但最好不要依赖它现在我想象.而且你需要过滤出看不见的东西,比如.和..无论如何.)

  • 这就是我要发布的内容.我认为你的解决方案是要走的路. (2认同)

rg8*_*g88 14

这将为您计算您的目录中的内容.我将离开关于只计算图像的部分给我,因为我即将falll aaasssllleeelppppppzzzzzzzzzzzzzz.

iterator_count(new DirectoryIterator('path/to/dir/'));
Run Code Online (Sandbox Code Playgroud)


hah*_*ute 5

我是这样做的:

$files = scandir($dir);
$x = count($files);
echo $x;
Run Code Online (Sandbox Code Playgroud)

但它也很重要.和..