how to display folders and sub folders from dir in PHP(如何在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
.在数组上使用 sort
和 foreach
循环来打印列表.
Collect the directory names in an array instead of echo
ing 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中显示目录中的文件夹和子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在PHP中显示目录中的文件夹和子文件夹


- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01