在PHP中按日期对文件排序 [英] sort files by date in PHP

查看:74
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆