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

查看:342
本文介绍了如何在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

但是在星期一,它的显示是这样的

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将其命名.在数组上使用sort并使用foreach循环打印列表.

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.

因此,您可以使用$dirnames[] = $dirname;(而不是echo ("$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天全站免登陆