【问题标题】:How to sort by date using PHP opendir()如何使用 PHP opendir() 按日期排序
【发布时间】:2024-05-02 00:35:01
【问题描述】:

我有一个目录,里面装满了我想要回显的文件。如果文件是图像,则图像本身会被回显。如果文件不是图片,则回显文件名。

以下代码完美运行,但我似乎无法按日期排序。文件随机回显。

我将如何使文件按最后修改(最新的在前)排序。

<?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);
}
?>

【问题讨论】:

标签: php directory echo opendir


【解决方案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;
}

【讨论】: