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
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));
...
Put your code into a function so you can call it for each directory at a particular level.
function all_subdirectories($directory) {
$files = glob("$directory/*");
return array_filter($files, 'is_dir');
}
Here's code that will create a 2-dimensional array with every level.
$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);
For just 3 levels it's simpler:
$level1 = all_subdirectories("MainFolder");
$level2 = all_subdirectories("MainFolder/*");
$level3 = all_subdirectories("MainFolder/*/*");