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

£可爱£侵袭症+ 提交于 2019-12-11 17:13:39

问题


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 suggestion is very appreciated, regards from Argentina!


回答1:


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


来源:https://stackoverflow.com/questions/6557980/how-can-i-display-latest-uploaded-image-first-phpcss

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!