计算文件夹中子文件夹的数量

时间:2015-01-20 23:16:29

标签: php

PHP代码

<?php
    echo '<ul class="DirView">';
    $path = "../Desktop/";
    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileinfo) {
        if ($fileinfo->isDir() && !$fileinfo->isDot()) {
            echo '<li>'.$fileinfo->getFilename().'</li>';
        }
    }
    echo '</ul>';
?>

问题

我希望能够计算我所选位置中的文件夹数量,以便使用此脚本为子文件夹的数量执行while循环来执行更多操作。

1 个答案:

答案 0 :(得分:3)

count($dir)将是最简单的解决方案,但不幸的是它在这里不起作用。 (总是1)

所以这是带有计数器变量的解决方案:

<?php
    echo '<ul class="DirView">';
    $path = "..";
    $dir = new DirectoryIterator($path);
    $counter = 0;
    foreach ($dir as $fileinfo) {
        if ($fileinfo->isDir() && !$fileinfo->isDot()) {
            echo '<li>'.$fileinfo->getFilename().'</li>';
            $counter++;
            // do your while loop here
        }
    }
    echo '</ul>';
    echo "There are $counter files in this directory.";
?>