如何在PHP中显示目录中的文件夹和子文件夹 [英] how to display folders and sub folders from dir in PHP

查看:26
本文介绍了如何在PHP中显示目录中的文件夹和子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取包含文件夹和子文件夹的列表我有以下内容可以让我获取文件夹和子文件夹但我需要像下面这样整理它我一直在尝试但我不知道如何我会绕过.

I am trying to get a list with folders and sub folders i have the following that allows me to get the folders and sub folders but i needed it to be sorted out like the e.g below i have been trying but i dont know how i would get around.

Root/
Root/Images
Root/Images/UserImages

Root/Text/
Root/Text/User1/
Root/Text/User1/Folder2

但是在monent它的显示是这样的

but at the monent its display like this

Root/css/
tree/css/
js/
images/

PHP 代码:

    function ListFolder($path)
{

    $dir_handle = @opendir($path) or die("Unable to open $path");

    //Leave only the lastest folder name
    $dirname = end(explode("/", $path));

    //display the target folder.
    echo ("$dirname/");
    while (false !== ($file = readdir($dir_handle)))
    {
        if($file!="." && $file!="..")
        {
            if (is_dir($path."/".$file))
            {
                //Display a list of sub folders.
                ListFolder($path."/".$file);
                echo "<br>";
            }
        }
    }


    //closing the directory
    closedir($dir_handle);
}

    ListFolder("../");

谢谢

推荐答案

将目录名收集到一个数组中,而不是直接echo.在数组上使用 sortforeach 循环来打印列表.

Collect the directory names in an array instead of echoing them directly. Use sort on the array and a foreach-loop to print the list.

所以代替 echo ("$dirname/"); 你会使用 $dirnames[] = $dirname; (使 $dirnames 全局并在你之前初始化它第一次调用ListFolder").然后在递归运行ListFolder"之后,您将执行 sort($dirnames); 然后像这样的输出:

So instead of echo ("$dirname/"); you would use $dirnames[] = $dirname; (make $dirnames global and initialize it before your first call of "ListFolder"). Then after the recursive run of "ListFolder", you'd execute sort($dirnames); and then something like this for the output:

foreach ($dirnames as $dirname)
{
  echo $dirname . '<br />';
}

这篇关于如何在PHP中显示目录中的文件夹和子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆