开发者

How can I display latest uploaded image first? (PHP+CSS)

I am new to PHP and basically I am trying to display an image gallery that retrieves photos from a folder. The thing is, I want the image with the most recent upload date to appear at the very beginning, and so on until the oldest one in the bottom.

This is what my PHP looks like (the important bit I guess)

$files = scandir('uploads/thumbs');
$ignore = array( 'cgi-bin', '.', '..');
foreach ($files as $file) {
    if(!in_array($file, $ignore)) {
        echo '<img src="uploads/thumbs/' . $file . '" />';
         }
}

I would like to know if there's a way by PHP or maybe with a little help of CSS to display them in reverse order, making the newest one always to appear at the top of the page.

Any help or 开发者_JAVA技巧suggestion is very appreciated, regards from Argentina!


Next to your $files you can obtain the modification time of each file and then sort the $files array based on the time values acquired. A function which sorts two or more arrays with the value of an array is array_multisort:

$files = scandir($path);
$ignore = array( 'cgi-bin', '.', '..');

# removing ignored files
$files = array_filter($files, function($file) use ($ignore) {return !in_array($file, $ignore);});

# getting the modification time for each file
$times = array_map(function($file) use ($path) {return filemtime("$path/$file");}, $files);

# sort the times array while sorting the files array as well
array_multisort($times, SORT_DESC, SORT_NUMERIC, $files);

foreach ($files as $file) {
    echo '<img src="uploads/thumbs/' . $file . '" />';
}


If you have your images in a database you can just do

$sql1 = "SELECT * FROM images ORDER BY img_id DESC";

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜