按日期对数组进行排序,然后在readdir之后进行分页


Sort array by date before pagination after readdir

我有代码来显示带有分页的文件夹中的图像。我需要改变它,使它显示最新的图像首先在第一页,最老的在最后一页。我试过几种方法,但似乎都不起作用。请帮助!

$mydir = opendir($maindir) ;
$limit = 78;
$offset = ((int)$_GET['offset']) ? $_GET['offset'] : 0; 
$files = array();
$page='';
$exclude = array( ".", "..", "index.php",".htaccess","guarantee.gif") ;
while($fn = readdir($mydir))
{
    if (!in_array($fn, $exclude)) 
    {
        $files[] = $fn;;
    }
}
closedir($mydir);
sort($files);
$newICounter = (($offset + $limit) <= sizeof($files)) ? ($offset + $limit) : sizeof($files);
for($i=$offset;$i<$newICounter;$i++) {
    //SHOW THE IMAGES HERE
};  

您可以根据文件修改时间对文件进行排序:

<?php
    $mydir = opendir($maindir) ;
    $limit = 78;
    $offset = ((int)$_GET['offset']) ? $_GET['offset'] : 0; 
    $files = array();
    $page='';
    $exclude = array( ".", "..", "index.php",".htaccess","guarantee.gif") ;
    while(false !== ($img_file = readdir($mydir))){
        if (!in_array($img_file, $exclude)){
            # <<<<<<<<<<<<<< CHANGE 1 <<<<<<<<<<<<<<<<
            //Put the creation date as the array's key:
            $files[date('Y m d, H:i:s',filemtime($img_file))] = $img_file;
        }
    }
    closedir($mydir);
    # <<<<<<<<<<<<<< CHANGE 2 <<<<<<<<<<<<<<<<  
    //order files by date in ascending order:
    ksort($files);
    //reverse the array (you need the newest files first)
    $files = array_reverse($files, false);      
        /*NOTE: in this point you have your images in $files array which are ordered by the file modification time of each file, so you only need the code to display them. I don't know how are you displaying your images, but that is the easiest part of the problem.*/
    foreach($files as $a_image){
echo "<img href='" . $maindir . $a_image ."' alt='Image not found' width='100%' height='auto'/>"; 
}
?>

很难在所有平台上获得文件的确切创建时间。所以我建议大家在创建文件时将当前日期与文件名连接起来