请马上登录,朋友们都在花潮里等着你哦:)
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 马黑黑 于 2025-4-24 21:50 编辑
PHP获取子目录及其文件的方法很多,本文使用PHP内置函数 glob 简单实现,用函数返回关联数组的形式达成目标。
function listDirs($dir) {
if (!is_dir($dir)) return []; // 目录若不存在返回空数组
$file_ar = array(); // 装载目录及其下文件(关联数组)
$ds = glob($dir . "*", GLOB_ONLYDIR); // 使用 glob 先获取子目录
if (count($ds) < 1) return []; // 若没有子目录返回空数组
// 遍历子目录
foreach ($ds as $d) {
// 使用 glob 获得 $d 子目录下所有资源(目录和文件)
$files = glob($d . "/{,.}*", GLOB_BRACE);
// 遍历每一个资源
foreach ($files as $file) {
// 如果是文件则加入到该目录关联数组
if (is_file($file )) {
$file_ar[$d][] = $file;
}
}
}
return $file_ar; //返回数组
}
// 应用示例:注意目录名末尾符号 /
$allFiles = listDirs("./");
echo ("<pre>");
print_r($allFiles);
echo "</pre>";
打印结果类似下面这样:
Array
(
[./2025] => Array
(
[0] => ./2025/Highgh歌 (Live).mp3
[1] => ./2025/TruE.mp3
[2] => ./2025/《篇外》.mp3
[3] => ./2025/来日方长.mp3
[4] => ./2025/苍生 (Timeless Romance).mp3
[5] => ./2025/风月.mp3
)
[./uploads] => Array
(
[0] => ./uploads/index.php
[1] => ./uploads/index_bak.php
[2] => ./uploads/upload.html
[3] => ./uploads/upload.php
)
)
这就是PHP关联数组的数据结构,也可以根据需要修改 listDirs 函数以便拿到自己所需要的数据。
|