【问题标题】:PHP scan folders then files while echoingPHP在回显时扫描文件夹然后文件
【发布时间】:2014-02-14 14:28:44
【问题描述】:

我一直在尝试打印列表中的文件,同时获取文件、文件夹和子文件夹。 我可以把所有东西都拿出来,但我想先显示文件夹。 有没有办法做到这一点?

到目前为止我的代码:

function getFiles($path) {
    foreach (new DirectoryIterator($path) as $file) {
            if($file->isDot()) continue;

            if($file->isDir())
                echo "<li class='folder'>\n";
            else
                echo "<li>\n";

                echo "<a href='#'>" . $file->getFilename() . "</a>\n";
            if ($file->isDir()) {
                echo "<ul>\n";
                getFiles($file->getPathname());
                echo "</ul>\n";
            }
            echo "</li>\n";

    }
}

希望你能帮帮我!

【问题讨论】:

    标签: php recursion directory


    【解决方案1】:

    将它们添加到临时数组中,而不是 echo。我将创建一个数组名称$directories 和一个数组名称$files,然后您可以循环遍历这两个数组和echo

    类似这样的:

    function getFiles($path) {
        $directories = array();
        $files = array();
        foreach (new DirectoryIterator($path) as $file) {
            if ($file->isDot())
                continue;
    
            if ($file->isDir())
                $directories[] = $file;
            else
                $files[] = $file;
        }
        foreach($directories as $file) {
            echo "<li class='folder'>\n";
                echo "<a href='#'>" . $file->getFilename() . "</a>\n";
                echo "<ul>\n";
                getFiles($file->getPathname());
                echo "</ul>\n";
            echo "</li>\n";
        }
        foreach($files as $file) {
            echo "<li>\n";
                echo "<a href='#'>" . $file->getFilename() . "</a>\n";
            echo "</li>\n";
        }
    }
    

    【讨论】:

    • 我如何才能递归地回显文件夹内的文件?
    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2010-12-11
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多