I am using below code to generate photo gallery from a folder. How can i sort thumbnails date wise.
<?php
/* settings */
$image_dir = 'photo_gallery/';
$per_column = 6;
/* step one: read directory, make array of files */
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
if(strstr($file,'-thumb'))
{
$files[] = $file;
}
}
}
closedir($handle);
}
/* step two: loop through, format gallery */
if(count($files))
{
foreach($files as $file)
{
$count++;
echo '<a class="photo-link" rel="one-big-group" href="',$image_dir,str_replace('-thumb','',$file),'"><img src="',$image_dir,$file,'" width="100" height="100" /></a>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo '<p>There are no images in this gallery.</p>';
}
?>
To hit your question directly, while you're reading the dir for files, you can get info about the files using some native php functions...
When a file was last accessed: fileatime - http://www.php.net/manual/en/function.fileatime.php
When a file was created: filectime - http://www.php.net/manual/en/function.filectime.php
When a file was modified: filemtime - http://php.net/manual/en/function.filemtime.php
These return the time, formatted as unix time.
For simplicity, I would use filectime to find the time, and use that value as the KEY in the $files array, like so: $files[filectime($file)] = $file;
Then you can use a simple array sorting function like ksort() to order them outside the loop, before you start step two.
Now... Going slightly deeper... I would probably use a database to store information like this, instead of hitting the file system every time the page is loaded. It will be a little more overhead in development, but depending on the size of the dir, could save you a lot of time and processing power.
TESTED 2012-06-23
/* settings */ $image_dir = 'photo_gallery/'; $per_column = 6; /* step one: read directory, make array of files */ if ($handle = opendir($image_dir)) { while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { if(strstr($file,'-thumb')) { $files[filemtime($image_dir . $file)] = $file; } } } closedir($handle); } /* step two: loop through, format gallery */ if(count($files)) { krsort($files); foreach($files as $file) { $count++; echo '<a class="photo-link" rel="one-big-group" href="',$image_dir,str_replace('-thumb','',$file),'"><img src="',$image_dir,$file,'" width="100" height="100" /></a>'; if($count % $per_column == 0) { echo '<div class="clear"></div>'; } } } else { echo '<p>There are no images in this gallery.</p>'; } ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.