如何以与readdir相反的顺序制作PHP显示文件?

时间:2011-03-19 05:26:30

标签: php

我正在使用它按照添加到目录中的顺序返回图像,但我希望它们从最新到最旧订购。我该怎么做?感谢

<?
$handle = @opendir("images");

if(!empty($handle)) {
  while(false !== ($file = readdir($handle))) {
    if(is_file("images/" . $file))
      echo '<img src="images/' . $file . '"><br><br>';
  }
}

closedir($handle);
?>

3 个答案:

答案 0 :(得分:2)

如果您希望从最新到较旧订购,那么您不能只依赖readdir。该命令可能是任意的。您需要按时间戳排序:

$files = glob("images/*");    // or opendir+readdir loop

$files = array_combine($files, array_map("filemtime", $files));
arsort($files);               // sorts by time

$files = array_keys($files);  // just leave filenames

答案 1 :(得分:0)

我认为最简单的方法是将文件读入数组,反转并输出反转数组:

<?php

$handle = @opendir("images");

if(!empty($handle))
{
    $files = array();
    while(false !== ($file = readdir($handle)))
    {
        if(is_file("images/" . $file))
            $files[] = $file;
    }

    foreach(array_reverse($files) as $file) {
        echo '<img src="images/' . $file . '"><br><br>';
    }
}

closedir($handle);

?>

答案 2 :(得分:0)

像这样:

<?
$handle = @opendir("images");

$files = array();
if(!empty($handle)) {
  while(false !== ($file = readdir($handle))) {
    if(is_file("images/" . $file))
      $files[] = $file;
  }
}

closedir($handle);

// flip the array over
$files = array_reverse($files);

// display on screen
foreach ($files as $file)
  echo '<img src="images/' . $file . '"><br><br>';
?>