dtn913117 2018-09-24 18:17
浏览 51
已采纳

如何使用glob创建子目录数组

I have the following directory structure:

MainFolder
    Folder1
        Folder1-1
             Folder1-1-1  
             Folder1-1-2
             Folder1-1-3    
        Folder1-2
             Folder1-2-1  
             Folder1-2-2
             Folder1-2-3  
    Folder2
        Folder2-1
             Folder2-1-1  
             Folder2-1-2
             Folder2-1-3  
        Folder2-2
             Folder2-2-1  
             Folder2-2-2
             Folder2-2-3

I'm trying to create 3 arrays

1 - array of all subfolders of MainFolder (Folder1, Folder2..etc)

2 - array of subfolders inside of Folder1, Folder2, etc (e.g:Folder1-1...folder2-1...)

3 - array of subfolders inside Folder1-1..., Folder1-2..., etc

this way I can only filter the subdirectories of the current directory:

//path to directory to scan
$directory = "MainFolder/";

//get all files in specified directory
$files = glob($directory . "*");

//print each file name
foreach($files as $file)
{
 //check to see if the file is a folder/directory
 if(is_dir($file))
 {
  echo $file;
 }
}

but how do I, for glob to filter the current directory and automatically group into array as I showed in the example?

I already saw that RecursiveDirectoryIterator exists but I did not understand how to put it in different arrays

  • 写回答

2条回答 默认 最新

  • dougai2427 2018-09-24 20:10
    关注

    You have a fixed low depth, so you don't really need recursive imho.

    You can use wildcard * to mark different levels and GLOB_ONLYDIR to retrieve folders only :

    $level1 = glob('MainFolder/*', GLOB_ONLYDIR);
    $level2 = glob('MainFolder/*/*', GLOB_ONLYDIR);
    $level3 = glob('MainFolder/*/*/*', GLOB_ONLYDIR);
    

    If you want to store the last folder instead of full path you can use array_map() and basename() :

    $level1 = array_map('basename', glob('MainFolder/*', GLOB_ONLYDIR));
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?