0

对php一无所知,但我有这个脚本可以读取一个文件夹并显示一个缩略图库,问题是它按字母顺序显示。已经在网上搜索并看到这种方法可以做到这一点,但不知道从哪里开始任何帮助将不胜感激。

这是脚本

$sitename = $row_wigsites['id'];     
$directory = 'sites/'.$sitename.'/pans';
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;

$dir_handle = @opendir($directory) or die("There is an error with your image directory!");

while ($file = readdir($dir_handle)) 

{

if($file=='.' || $file == '..') continue;

$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));

$title = implode('.',$file_parts);
$title = htmlspecialchars($title);


$nomargin='';

if(in_array($ext,$allowed_types))
{

    if(($i+1)%4==0) $nomargin='nomargin';

    echo '
    <div class="pic '.$nomargin.'" style="background:url('.$directory.'/'.$file.') no-repeat 50% 50%;">
    <a href="'.$directory.'/'.$file.'" title="Panoramic Stills taken at '.$title.'°" rel="pan1" target="_blank">'.$title.'</a>
    </div>';

    $i++;
}
}

closedir($dir_handle);
4

4 回答 4

1

尝试使用glob而不是 opendir,例如:

$i=0;
foreach (glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file){
    if($file=='.' || $file == '..') continue;
    $file_parts = explode('.',$file);
    $ext = strtolower(array_pop($file_parts));
    $title = basename($file);
    $title = htmlspecialchars($title);
    $nomargin='';
    if(($i+1)%4==0) $nomargin='nomargin';
    echo '
    <div class="pic '.$nomargin.'" style="background:url('.$file.') no-repeat 50% 50%;">
    <a href="'.$file.'" title="Panoramic Stills taken at '.$title.'°" rel="pan1" target="_blank">'.$title.'</a>
    </div>';
    $i++;
}

Glob 应该返回排序后的文件列表。

编辑:感谢 Doug Neiner 的提示;)

于 2010-01-18T16:03:06.960 回答
0

添加如下所示的排序行

$file_parts = explode('.',$file);
sort($file_parts) or die("sorting failed");
$ext = strtolower(array_pop($file_parts));
于 2010-01-18T15:59:58.090 回答
0

将文件中的值放入数组中可能是最简单的,然后在将数组输出到页面之前对数组进行排序。

于 2010-01-18T16:02:36.807 回答
0

@Habicht 代码工作正常,但正确的缩略图不再工作,因为缩略图目录引用已被删除:

所以我尝试这样:

$i=0;
foreach (glob($directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file)
{
  foreach (glob($thumbs_directory.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE) as $file2)
  {
     if($file=='.' || $file == '..') continue;
     $file_parts = explode('.',$file);
     $ext = strtolower(array_pop($file_parts));
     $title = basename($file);
     $title = htmlspecialchars($title);
     $title = str_replace("_"," ",$title);
     $nomargin='';
     if(($i+1)%4==0) $nomargin='nomargin';
     echo '<div class="pic '.$nomargin.'" style="background:url('.$file2.') no-repeat 50% 50%;">
       <a href="'.$file.'" title="'.$title.'" target="_blank">'.$title.'</a>
     </div>';
     $i++;
  }
}

缩略图工作正常,但任何缩略图的参考图像始终相同 - $directory 中的第一个图像文件。我确信还有其他方法可以将这些 foreach 语句组合在一起以一次修复所有问题。

于 2013-03-10T22:12:10.587 回答