Php 如何按日期对照片库脚本排序
我正在使用下面的代码从文件夹生成照片库。 如何按日期对缩略图进行排序Php 如何按日期对照片库脚本排序,php,sorting,photo,photo-gallery,Php,Sorting,Photo,Photo Gallery,我正在使用下面的代码从文件夹生成照片库。 如何按日期对缩略图进行排序 <?php /* settings */ $image_dir = 'photo_gallery/'; $per_column = 6; /* step one: read directory, make array of files */ if ($handle = opendir($image_dir)) {
<?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>';
}
?>
要直接回答您的问题,在阅读文件目录时,您可以使用一些本机php函数获取有关文件的信息 上次访问文件的时间:fileatime- 创建文件时:filectime- 修改文件时:filemtime- 它们返回时间,格式为unix时间 为简单起见,我将使用filectime来查找时间,并将该值用作$files数组中的键,如下所示:$files[filectime($file)]=$file 然后,在开始第二步之前,可以使用一个简单的数组排序函数(如ksort())在循环外对它们进行排序 现在。。。稍微深入一点。。。我可能会使用数据库来存储这样的信息,而不是每次加载页面时都访问文件系统。这将在开发中增加一点开销,但根据目录的大小,可以节省大量时间和处理能力 测试日期:2012-06-23
/*设置*/
$image_dir='photo_gallery/';
每列$6;
/*第一步:读取目录,制作文件数组*/
如果($handle=opendir($image\u dir)){
while(false!=($file=readdir($handle)))
{
如果($file!='.&&$file!='..'))
{
if(strstr($file,'-thumb'))
{
$files[filemtime($image\u dir.$file)]=$file;
}
}
}
closedir($handle);
}
/*第二步:循环,格式化库*/
如果(计算($文件))
{
krsort($文件);
foreach($files作为$file)
{
$count++;
回声';
如果($count%$per_column==0){echo';}
}
}
其他的
{
echo“此库中没有图像。”;
}
?>
谢谢,顺便说一句,我使用了你的建议,但不起作用。你可以修改代码本身吗。以下代码仅供参考:谢谢。修改后的代码对文件进行排序,但最后上载的图像将转到按钮而不是顶部(第一个图像)。你能让我知道我该怎么做才能先上传最后一张图片吗?你的意思是顺序颠倒了,还是有一张特定的图片显示在底部,应该在顶部?我现在明白了,我已经看到了标记。。。ksort函数正在对asc进行排序,您需要描述。。。我已经更新了上面的代码,使用krsort而不是ksort。
/* 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>';
}
?>