How to sort by date using PHP opendir()

↘锁芯ラ 提交于 2019-12-25 07:36:58

问题


I have a directory full of files that I am trying to echo out. If the file is an image, the image itself is echoed out. If the file is not an image, the name of the file is echoed out.

This code below works perfectly however I can't seem to get the order sorted by date. The files are randomly echoed out.

How would I make it so that the files are sorted by last modified (latest first).

<?php


$blacklist = array("index.php");
$ext = pathinfo($files, PATHINFO_EXTENSION);

if ($handle = opendir('.')) {

    $valid_image = array("jpg", "jpeg", "png", "gif");

    while (false !== ($entry = readdir($handle))) { 
       krsort($entry);

        if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {

            $exploded = explode('.', $entry);

            if(in_array(end($exploded), $valid_image))
            {
              echo "<div><h4>"; echo date('d F Y', filemtime($file)) . "</h4><a href='" . $entry . "'><img src='".$entry."'></a></div><hr>";
            }
            else
            {
              echo "<div><h4>"; echo date('d F Y', filemtime($file)) . "</h4><a href='" . $entry . "'>" . $entry . "</a></div>";
            }
        } 
    }
    closedir($handle);
}
?>

回答1:


// Create an empty array, outside your loop
$files = array();

while (false !== ($entry = readdir($handle))) { 
    if(in_array(end($exploded), $valid_image)){

       // Instead of echoing the string, add it to the array, using filemtime as the array key
       $files[filemtime($file)] = "<div><h4>".date('d F Y', filemtime($file)) . "</h4><a href='$entry'><img src='$entry'></a></div><hr>";

    } else...
}

// reverse sort on the array
krsort($files);        

// output the array in a loop
foreach($files as $file){
    echo $file;
}


来源:https://stackoverflow.com/questions/33767060/how-to-sort-by-date-using-php-opendir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!