sort files by date in PHP

后端 未结 5 1620
天涯浪人
天涯浪人 2020-11-22 07:15

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

5条回答
  •  庸人自扰
    2020-11-22 07:58

    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 "$file$lastModified";
            }
        }
    }
    

    Not tested, but that's how to do it.

提交回复
热议问题