how to display folders and sub folders from dir in PHP

百般思念 提交于 2019-12-28 18:45:08

问题


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


回答1:


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.

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 />';
}



回答2:


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:

    $dir = '/path/to/directory';
    $result = array();

    if (is_dir($dir)) {
            $iterator = new RecursiveDirectoryIterator($dir);
            foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {                    
                if (!$file->isFile()) {
                    $result[] = 'path: ' . $file->getPath(). ',  filename: ' . $file->getFilename();
                }
            }

    }

This should do the trick. Good luck ;)




回答3:


with this code, you will get lists with subdirectories (but set your foldername)

<?php
$path = realpath('yourfolder/examplefolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
        echo "$filename\n";
}
?>


来源:https://stackoverflow.com/questions/4204728/how-to-display-folders-and-sub-folders-from-dir-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!