如何在 PHP 中显示 dir 中的文件夹和子文件夹
我正在尝试获取包含文件夹和子文件夹的列表,我有以下内容,可以让我获取文件夹和子文件夹,但我需要像下面的示例一样对它进行排序,我一直在尝试,但我不知道如何获取大约。
Root/
Root/Images
Root/Images/UserImages
Root/Text/
Root/Text/User1/
Root/Text/User1/Folder2
但目前它的显示如下
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("../");
谢谢
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 CODE:
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("../");
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将目录名称收集到数组中,而不是直接回显它们。对数组使用
sort
并使用foreach
循环来打印列表。因此,您可以使用
$dirnames[] = $dirname;
而不是echo ("$dirname/");
(使 $dirnames 全局化并在第一次调用之前初始化它) “列表文件夹”)。然后,在递归运行“ListFolder”之后,您将执行sort($dirnames);
,然后执行类似以下的输出:Collect the directory names in an array instead of
echo
ing them directly. Usesort
on the array and aforeach
-loop to print the list.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 executesort($dirnames);
and then something like this for the output:您可以使用 DirectoryIterator 或更好的 RecursiveDirectoryIterator 来实现您想要的php SPL.php
这是一个关于如何使用它的简单示例:
这应该可以解决问题。祝你好运 ;)
you can achive what you want with the DirectoryIterator or better the RecursiveDirectoryIterator from the php SPL.
here is a quick example on how to use this:
This should do the trick. Good luck ;)
使用此代码,您将获得包含子目录的列表(但设置您的文件夹名称)
with this code, you will get lists with subdirectories (but set your foldername)