我已经修改并清理了别人写的这个PHP脚本。在我的WAMP服务器上,它会按字母顺序列出图像(它们都命名为001.jpg~110.jpg),但在LAMP服务器上,我认为它们是按修改日期组织的。。。不管是什么,都不是按文件名。它们都是JPEG图像,所以我不担心按类型排列。
那么,我该如何修改这个脚本以按字母顺序列出图像呢?
function getPictures()
{
global $page, $per_page, $has_previous, $has_next;
if ($handle = opendir('tour/'))
{
$lightbox = rand();
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
if ($skip != 0 ) {$has_previous = true;}
while ($count < $skip && ($file = readdir($handle)) !== false )
{
if (!is_dir($file) && ($type = getPictureType($file)) != '' ) {$count++;}
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false )
{
if (!is_dir($file) && ($type = getPictureType($file)) != '' )
{
if (!is_dir('thumbs/')) {mkdir('thumbs/');}
if (!file_exists('thumbs/'.$file)) {makeThumb('tour/'.$file,$type );}
echo '<li><a href="tour/'.$file.'" rel="lightbox['.$lightbox.']">';
echo '<img src="thumbs/'.$file.'" alt="" />';
echo '</a></li>';
$count++;
}
}
echo '</ul>';
while (($file = readdir($handle)) !== false)
{
if (!is_dir($file) && ($type = getPictureType($file)) != '' )
{
$has_next = true;
break;
}
}
}
}
您可以使用默认按字母顺序排序的scandir
,而不是使用readdir
。
默认情况下,排序顺序是按字母升序排列的。如果可选排序顺序设置为SCANDIR_SORT_DESCENDING,然后排序顺序是按字母降序排列的。如果设置为SCANDIR_SORT_NONE,则结果未排序。
请记住,scandir
返回一个文件名数组,而readdir
返回一个条目名称。
或者,您可以将文件名读入数组,并使用natsort
对其进行排序。
// Orders alphanumeric strings in the way a human being would
natsort($arr);
Array
(
[3] => img1.png
[2] => img2.png
[1] => img10.png
[0] => img12.png
)
看起来像一个"lightbox"函数,如果是的话,这是我上面发布的函数的完整修改版本。。。
function getPictures()
{
if ($handle = opendir('tour/'))
{
global $page, $per_page, $has_previous, $has_next;
$lightbox = rand();
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
$file = scandir('tour/');
$images = array();
foreach ($file as $key => $value)
{
if (!is_dir('tour/'.$value) && ($type = getPictureType('tour/'.$value)) != '' )
{
array_push($images,$value);
}
}
natsort($images);
$count = 0;
$start = $per_page*$page;
$end = $start+$per_page - 1;
foreach ($images as $key => $value)
{
if ($key>=$start && $key<=$end)
{
echo '<li><a href="tour/'.$value.'" rel="lightbox['.$lightbox.']"><img src="thumbs/'.$value.'" alt="" /></a></li>';
$count++;
}
}
$not_first = $end+1;
if ($key>$end) {$has_next = true;}
if ($not_first!=$per_page) {$has_previous = true;}
echo '</ul>';
}
}