在 PHP 中按日期对文件进行排序 [英] sort files by date in PHP
问题描述
我目前有一个 index.php 文件,它允许我输出同一目录中的文件列表,输出显示名称然后我使用 filemtime() 函数来显示文件被修改的日期.我现在的问题是,我将如何对输出进行排序以显示最新修改的文件?我一直在思考如何做到这一点.如果我只是用 mysql 交互来做,那就完全没有问题了.请举例说明如何从最新修改的文件开始排序和输出文件列表.这就是我现在拥有的
I currently have an index.php file which allows me to output the list of files inside the same directory, the output shows the names then I used filemtime() function to show the date when the file was modified. my problem now is, how will I sort the output to show the latest modified file ?, I've been thinking for awhile how to do this. if only I am doing it with mysql interaction there will be no problem at all. please show me an example how to sort and output the list of files starting from the latest modified one. this is what i have for now
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
echo "<tr><td><input type="checkbox" name="box[]"></td><td><a href="$file" target="_blank">$file</a></td><td>$lastModified</td></tr>";
}
}
}
closedir($handle);
}
推荐答案
您需要将文件放入数组中,以便对最后修改的文件进行排序和查找.
You need to put the files into an array in order to sort and find the last modified file.
$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);
foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type="checkbox" name="box[]"></td><td><a href="$file" target="_blank">$file</a></td><td>$lastModified</td></tr>";
}
}
}
未经测试,但就是这样做的.
Not tested, but that's how to do it.
这篇关于在 PHP 中按日期对文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!