+ 1

PHP: How do I sort and show images from a dir?

How do I sort and show images from a dir? I can't find anything useful in the Internet.

27th Dec 2016, 9:11 AM
posajpous
6 Réponses
+ 4
You can use the filemtime() function to find the modification date of each file. This can be used as a key to sort the array using uksort() before it is processed in the loop. This will put the array in ascending order of file modification time, i.e. those with the earliest mtime first. You can then either reverse the array, or iterate through it backwards. backwards. <?php function mtimecmp($a, $b) { $mt_a = filemtime($a); $mt_b = filemtime($b); if ($mt_a == $mt_b) return 0; else if ($mt_a < $mt_b) return -1; else return 1; } $images = glob($dirname."*.jpg"); usort($images, "mtimecmp"); array_reverse($images); foreach ($images as $image) { echo '<img src="'.$image.'" height ="400"/><br />'; } ?> (Iterating backwards is more efficient...) // ... usort($images, "mtimecmp"); for ($i = count($images) - 1; $i >= 0; $i--) { $image = $images[$i]; echo '<img src="'.$image.'" height ="400"/><br />'; } Dr.
27th Dec 2016, 10:10 AM
Tristan McCullen
Tristan McCullen - avatar
+ 4
passing filemtime() as the callback to uksort() won't work on its own. need a small utility function which interprets the result and returns an integer informing uksort(), ie: "Function cmp_function [the callback] should accept two parameters which will be filled by pairs of array keys. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
27th Dec 2016, 10:18 AM
Tristan McCullen
Tristan McCullen - avatar
+ 3
You'll need to perform in two steps: (a) read the directory contents and note last modified info (b) render the result $images = glob($dirname . '*.jpg'); $mostrecent = 0; $mostrecentimg = null; // scan foreach ($images as $image) { $imagemod = filemtime($image); if ($mostrecent < $imagemod) { $mostrecentimg = $image; $mostrecent = $imagemod; } } // display echo '<img src="' . $mostrecentimg . '" height="400"/><br />'; foreach($images as $image) { // the most recent was already output above so skip remainder this iteration if ($image == $mostrecentimg) continue; echo '<img src="' . $image . '" height="400"/><br />'; } Dr.
27th Dec 2016, 10:21 AM
Tristan McCullen
Tristan McCullen - avatar
+ 1
I know this code and I tried it already yesterday but didn't work either. Might xampp be the problem?
27th Dec 2016, 10:13 AM
posajpous
0
in what order do you want the images displayed?
31st Dec 2016, 5:09 AM
Simon
0
hahaha!
31st Dec 2016, 6:52 AM
บัก'ก 'ห่า เฟรม'ม คลเดิม'มม
บัก'ก 'ห่า เฟรม'ม คลเดิม'มม - avatar