使用 PHP 返回文件夹内的文件总数
是否有更好/更简单的方法来查找目录中的图像数量并将它们输出到变量?
Is there a better/simpler way to find the number of images in a directory and output them to a variable?
function dirCount($dir) {
$x = 0;
while (($file = readdir($dir)) !== false) {
if (isImage($file)) {$x = $x + 1}
}
return $x;
}
这样的方法好像很长,有没有更简单的方法?
This seems like such a long way of doing this, is there no simpler way?
注意:如果文件是图像,isImage() 函数返回 true.
Note: The isImage() function returns true if the file is an image.
推荐答案
查看 DirectoryIterator 的标准 PHP 库(又名 SPL):
Check out the Standard PHP Library (aka SPL) for DirectoryIterator:
$dir = new DirectoryIterator('/path/to/dir');
foreach($dir as $file ){
$x += (isImage($file)) ? 1 : 0;
}
(仅供参考,有一个名为 iterator_count() 的未记录函数,但我想现在最好不要依赖它.而且你需要过滤掉看不见的东西,比如 . 和 .. 无论如何.)
(FYI there is an undocumented function called iterator_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)
相关文章