首页 > 解决方案 > 如何使用 glob 创建子目录数组

问题描述

我有以下目录结构:

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

我正在尝试创建 3 个数组

1 - MainFolder 的所有子文件夹的数组(Folder1、Folder2..etc)

2 - Folder1、Folder2 等内部的子文件夹数组(例如:Folder1-1...folder2-1...)

3 - Folder1-1...、Folder1-2...等内的子文件夹数组

这样我只能过滤当前目录的子目录:

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

但是我如何让 glob 过滤当前目录并自动分组到数组中,如示例中所示?

我已经看到它RecursiveDirectoryIterator存在但我不明白如何将它放在不同的数组中

标签: phparraysglob

解决方案


你有一个固定的低深度,所以你真的不需要递归恕我直言。

您可以使用通配符 * 标记不同的级别,使用GLOB_ONLYDIR仅检索文件夹:

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

如果要存储最后一个文件夹而不是完整路径,可以使用array_map()basename()

$level1 = array_map('basename', glob('MainFolder/*', GLOB_ONLYDIR));
...

推荐阅读