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

时间:2015-08-22 13:48:42

标签: php pagination 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
};  

1 个答案:

答案 0 :(得分:0)

您可以按文件修改时间订购文件:

<?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'/>"; 
}
?>

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