+ 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.
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.
+ 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.
+ 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.
+ 1
I know this code and I tried it already yesterday but didn't work either. Might xampp be the problem?
0
in what order do you want the images displayed?
0
hahaha!