开发者

How do I make PHP display files in the opposite order that readdir does?

开发者 https://www.devze.com 2023-02-18 07:12 出处:网络
I\'m using this to return images in the order they were added to the directory, however I want them to be ordered from newest to older. How can I do it? Thanks

I'm using this to return images in the order they were added to the directory, however I want them to be ordered from newest to older. How can I do it? Thanks

<?
$h开发者_如何学Candle = @opendir("images");

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

closedir($handle);
?>


If you want them ordered from newest to older, then you cannot rely on just readdir. That order might be arbitrary. You'll need to sort them by timestamps:

$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


I think the easiest way is to read your files into an array, reverse it and output the reversed array:

<?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);

?>


Like this:

<?
$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>';
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消