普通网友 2019-08-15 08:43
浏览 83

列出目录和子目录并将每个级别存储在数组中

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

  • 写回答

1条回答

  • doujiongqin0687 2019-08-15 08:55
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档