Jump to content

Simple image sorting


murratw

Recommended Posts

I am trying to show images in a directory by date last modified. The code below is showing the oldest ones first then by file type.

 

How do I modify it to show all files by last uploaded to the directory? I want the newest ones showing first.

 

I am very new to PHP.

 

<?php

//Your folder
$files = glob("images/*.*");

$colCnt=0;
echo '<table border="0" style="width:1000px;">';

for ($i=1; $i<count($files); $i++)
  {
  $colCnt++;
  if ($colCnt==1)
  echo '<tr>';
  echo '<td width="20%" style="font-size:8.5px; font-family:arial">';

  $num = $files[$i];
   
echo ' 
   <a href="' . $num . '"><img class="thumb ImgBorder" src="'.$num.'" rel="lightbox" alt="random image"></a>'."  ";



  echo '</td>';

  if ($colCnt==6)
    {
    echo '</tr>';
    $colCnt=0;
    }
  }

echo '</table>';
?>

 

 

 

Link to comment
Share on other sites

The code below is showing the oldest ones first then by file type.

It's actually showing them in whatever order the operating system and file system says. That tends to be oldest to newest but isn't guaranteed.

 

 

glob() will get you an array of files. You need to sort this array based on whatever criteria you want, and usort is appropriate for that.

$files = glob("images/*.*");

function sortnewestfilesfirst($a, $b) {
    return filemtime(???) - filemtime(???);
}
usort($files, "sortnewestfilesfirst");

If I tell you that:

- usort() takes an array and a function to use to sort the array

- the function takes two arguments and must return: a number 0 for the reverse, and =0 if they're the same

- filemtime() returns the last modified time of a file as a Unix timestamp (ie, a number) with smaller numbers being older

can you replace the ???s with the appropriate variables?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.