Return total number of files within a folder using PHP(使用 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.)
这篇关于使用 PHP 返回文件夹内的文件总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 PHP 返回文件夹内的文件总数


基础教程推荐
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- php中的PDF导出 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- php中的foreach复选框POST 2021-01-01
- 将变量从树枝传递给 js 2022-01-01