[thelist] PHP directory sort by date

Jackson Yee jyee at vt.edu
Wed Jan 22 19:03:01 CST 2003


"Daniel Fascia" <danfascia at totalise.co.uk> wrote in message
news:3E35AE31 at mail.totalise.co.uk...
> 1) using the dir() class and praying it spits out results in date order

If it's a direct overlay of the filesystem API, it'll give you files in the
order that they are located in the directory file, meaning that it's not a
good alternative.

> 2) using readdir() and then making a date sort function for the array I
store.
> But god only knows how to write a date sort function...

[Disclaimer: I haven't touched PHP in three months while I've been busy with
projects for college & work, so this code should only be used for ideas]

Try

function LoadFiles($Pattern)
{
 $Files = array();

 $It = dir('[pattern]');

 if (! $It)
  die('Cannot list files for ' . $Pattern);

 while ($Filename = $it->read())
 {
  if ($Filename == '.' || $Filename == '..')
   continue;

  $LastModified = filemtime($Filename);
    $Files[] = array($Filename, $LastModified);
 }

 dir->close();

  return $Files;
}

function DateCmp($a, $b)
{
  return ($a[1] < $b[1]) ? -1 : 0;
}

function SortByDate(&$Files)
{
  usort($Files, 'DateCmp');
}

To test:

$Files = LoadFiles('*');
SortByDate($Files);
echo '<ol>';
foreach ($Files as $Filename)
{
  echo '<li>', $Filename, '</li>';
}
echo '</ol>';

usort(), along with several other functions, lets you use a function that
you define in order to make comparisons in sorting an array.  It's a very
handy function, and suits your purposes perfectly.

--
Regards,
Jackson Yee
jyee at vt.edu





More information about the thelist mailing list