可能重复:
文件创建时间
在PHP中,如何检索包含在按创建日期(或任何其他排序机制)排序的文件夹中的文件?
根据doc,readdir()函数:
文件名按文件系统存储的顺序返回.
将它们的信息保存到数组中,对数组进行排序,然后循环数组
if($h = opendir($dir)) {
$files = array();
while(($file = readdir($h) !== FALSE)
$files[] = stat($file);
// do the sort
usort($files, 'your_sorting_function');
// do something with the files
foreach($files as $file) {
echo htmlspecialchars($file);
}
}
Run Code Online (Sandbox Code Playgroud)
那是我的解决方案:
$fileList = array();
$files = glob('home/dir/*.txt');
foreach ($files as $file) {
$fileList[filemtime($file)] = $file;
}
ksort($fileList);
$fileList = array_reverse($fileList, TRUE);
print_r($filelist);
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
array(
(int) 1340625301 => '/home/dir/file15462.txt',
(int) 1340516112 => '/home/dir/file165567.txt',
(int) 1340401114 => '/home/dir/file16767.txt'
)
Run Code Online (Sandbox Code Playgroud)
然后使用"foreach"循环获取所需的文件.