php - 如何使用 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
存在但我不明白如何将它放在不同的数组中
解决方案
你有一个固定的低深度,所以你真的不需要递归恕我直言。
您可以使用通配符 * 标记不同的级别,使用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));
...
推荐阅读
- bit-manipulation - 某些正整数的按位与可以是负数吗?
- amazon-web-services - CloudFormation 堆栈类型:'AWS::IAM::Role'
- javascript - 从 json 响应中查找下一个最接近的日期和时间
- python - 结合2个for循环
- python - 如何创建一个财政年度的销售累计计数器?
- python - 追加列表理解时出现 Python 错误
- ios - 无法在 iOS 15 的侧边栏列表部分中同时呈现文本视图和 DatePicker
- python - 如何将脚本分解为更小的函数并创建 main.py?
- python - 如何修复 _pickle.PicklingError: can'tpickle : 它不是同一个对象
- javascript - 查找 TensorFlow.js 训练进度