繁体   English   中英

PHP回扫时扫描文件夹然后文件

[英]PHP scan folders then files while echoing

我一直在尝试打印列表中的文件,同时获取文件,文件夹和子文件夹。 我可以解决所有问题,但我想先显示文件夹。 有没有办法做到这一点?

我的代码到目前为止:

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";

    }
}

希望你能帮助我!

而不是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";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM