如何使用PHP opendir()按日期排序 [英] How to sort by date using PHP opendir()

查看:124
本文介绍了如何使用PHP opendir()按日期排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目录中充满了所有我想回显的文件.如果文件是图像,则图像本身会被回显.如果文件不是图像,则会回显文件名.

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

推荐答案

// 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;
}

这篇关于如何使用PHP opendir()按日期排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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