获取子文件夹的数量
Get the count of sub-folders
我使用 count(glob("test/*"))
来计算 test
文件夹中的子文件夹,但现在我在 test
文件夹中也有文件,而不仅仅是文件夹,我得到不正确的结果。有没有办法修改 glob
模式,使其 return 仅显示文件夹,而不显示文件?
我考虑过解决方法。获取文件夹和文件的总数,只获取文件的数量,然后,从整体的数量中减去文件的数量。
$total_items = count(glob("test/*"));
$total_files = count(glob("test/*.*"));
$folder_count = $total_items - $total_files;
这可行,但可能有更简单的方法。
我会尝试这样的事情,使用 readdir() 并使用 is_dir() (http://php.net/manual/en/function.opendir.php)
进行测试
$dir = "test";
$n = 0;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file != "." && $file != ".." && is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
$n++;
}
}
closedir($dh);
echo $n . " subdirectories in " . $dir;
您必须使用选项 GLOB_ONLYDIR
以 return 只有目录:
$total_items = count( glob("test/*", GLOB_ONLYDIR) );
如果目录名称中有一个点,例如 some.dir
,您当前的解决方案可能会失败。为了获得更好的结果,您可以检查每个结果以查看它们是否是文件。类似于:
count(array_filter(glob("test/*"), "is_dir"))
我使用 count(glob("test/*"))
来计算 test
文件夹中的子文件夹,但现在我在 test
文件夹中也有文件,而不仅仅是文件夹,我得到不正确的结果。有没有办法修改 glob
模式,使其 return 仅显示文件夹,而不显示文件?
我考虑过解决方法。获取文件夹和文件的总数,只获取文件的数量,然后,从整体的数量中减去文件的数量。
$total_items = count(glob("test/*"));
$total_files = count(glob("test/*.*"));
$folder_count = $total_items - $total_files;
这可行,但可能有更简单的方法。
我会尝试这样的事情,使用 readdir() 并使用 is_dir() (http://php.net/manual/en/function.opendir.php)
进行测试$dir = "test";
$n = 0;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file != "." && $file != ".." && is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
$n++;
}
}
closedir($dh);
echo $n . " subdirectories in " . $dir;
您必须使用选项 GLOB_ONLYDIR
以 return 只有目录:
$total_items = count( glob("test/*", GLOB_ONLYDIR) );
如果目录名称中有一个点,例如 some.dir
,您当前的解决方案可能会失败。为了获得更好的结果,您可以检查每个结果以查看它们是否是文件。类似于:
count(array_filter(glob("test/*"), "is_dir"))