You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何读取文本指定目录名并按修改日期排序后展示

解决方案

1. 修正读取文件夹白名单的代码

你原有代码中fopen/fclose是冗余的,file_get_contents会自动处理文件读写的开关,直接把文本内容按行拆分、去重去空,处理成白名单数组即可:

// 读取foldername.txt内容,按行拆分后去除前后空白、过滤空行,得到允许展示的文件夹名数组
$allowedFolderNames = array_filter(
    array_map(
        'trim',
        explode(PHP_EOL, file_get_contents('foldername.txt'))
    )
);

2. 筛选排序后的文件夹列表

glob返回的是完整路径,用basename()提取路径末尾的文件夹名,判断是否在白名单数组里即可,这里提供两种写法:

简化写法(推荐)

$filteredFolders = array_filter($folder, function ($fullDirPath) use ($allowedFolderNames) {
    return in_array(basename($fullDirPath), $allowedFolderNames);
});

遍历写法(更适合初学者理解逻辑)

$filteredFolders = [];
foreach ($folder as $fullDirPath) {
    $currentFolderName = basename($fullDirPath);
    // 仅保留白名单内的文件夹
    if (in_array($currentFolderName, $allowedFolderNames)) {
        $filteredFolders[] = $fullDirPath;
    }
}

最终效果

最终得到的$filteredFolders就是按修改日期倒序排序、仅包含foldername.txt指定的文件夹的结果,直接遍历该数组使用即可。


内容的提问来源于stack exchange,提问作者Bob D. Builder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:24:03