简体   繁体   中英

List directories and sub-directories and store every level in array

Want to scandir the root folder first, store the found directories in array (level 1). Then scandir each sub-directory that I've found and store them inside level 1, as level 2 and so on.

How can I do it with max 5 levels, and display on the screen as a folder tree.

I've made a terrible code with a lot of error, but half-working:

    $dir = "../pdoks"; //root folder
    $szint1 = scandir($dir); //szint1 means LEVEL 1

     unset($szint1[array_search('.', $szint1, true)]); //remove dots
     unset($szint1[array_search('..', $szint1, true)]);

    $countdir = count($szint1); //measure array's length

    for($i=0;$i<$countdir;$i++){            
        echo $szint1[$i] . "<br>"; //list directories in my given root          

        $szint2 = scandir($dir . "/" . $szint1[$i]); //szint2 as the new root folder 

         unset($szint2[array_search('.', $szint2, true)]); //remove dots
         unset($szint2[array_search('..', $szint2, true)]);

        $countdir2 = count($szint2); //measure 2nd array's length        

        for ($j=0;$j<$countdir2;$j++){
            echo $szint2[$j] . "<br>"; //list directories in new root   

            $szint3 = scandir($dir . "/" . $szint1[$j] . "/" . $szint2[$j]); //szint2 as the new root folder (../pdoks/szint1/szint2)

            unset($szint3[array_search('.', $szint3, true)]); //remove dots
            unset($szint3[array_search('..', $szint3, true)]);

            $countdir3 = count($szint3);

            for ($k=0;$k<$countdir3;$k++){
                echo $szint3[$k] . "<br>"; //list directories in new root level 3 folders
                //...etc
            }
        }

    }

Errors are:

"Undefined offset: 0" //or any number " scandir(../pdoks//PoosIstvan): failed to open dir: No such file or directory"

//seems level 2 missing from the path

There are plenty of examples on the web to get a recursive list of files and folders. You should avoid nesting loops, try to use a recusrive function call or an iterative way List all the files and folders in a Directory with PHP recursive function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM