我具有以下目录结构:
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
存在,但是我不明白如何将其放入不同的数组中
答案 0 :(得分:2)
您的深度固定不变,因此您实际上不需要递归imho。
您可以使用通配符*标记不同的级别,并使用 GLOB_ONLYDIR 仅检索文件夹:
struct
如果要存储最后一个文件夹而不是完整路径,则可以使用 array_map()和 basename():
$level1 = glob('MainFolder/*', GLOB_ONLYDIR);
$level2 = glob('MainFolder/*/*', GLOB_ONLYDIR);
$level3 = glob('MainFolder/*/*/*', GLOB_ONLYDIR);
答案 1 :(得分:1)
将代码放入函数中,以便可以在特定级别的每个目录中调用它。
function all_subdirectories($directory) {
$files = glob("$directory/*");
return array_filter($files, 'is_dir');
}
这里的代码将创建每个级别的二维数组。
$all_levels = array();
$dirs = array("MainFolder");
while (!empty($dirs)) {
$next_level = array();
foreach ($dirs as $dir) {
$next_level += all_subdirectories($dir);
}
if (!empty($next_level)) {
$all_levels[] = array_map('basename', $next_level);
}
$dirs = $next_level;
}
print_r($all_levels);
仅3个级别就更简单了:
$level1 = all_subdirectories("MainFolder");
$level2 = all_subdirectories("MainFolder/*");
$level3 = all_subdirectories("MainFolder/*/*");