Redo this Statement for Newest to Latest?

Discussion in 'PHP' started by cyclotron, Jul 2, 2008.

  1. #1
    Hey there fellow DP'ers!

    I got a PHP code that opendir's a directory and in alphabetical order displays the contents of the folder (images) in pages. I wish to convert this so instead of alphabetical it will be newest to last.

    if ($handle = opendir('defaultimages')) {
       while (false !== ($file = readdir($handle))) {
           if ($file != "." && $file != "css" && $file != "..") {
               $files[] = $file;
           }
       }
       closedir($handle);
    }
    
    $array_lowercase = array_map('strtolower', $files);
    array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $files);
    
    $count=0; $path = 'defaultimages/';
    $perpage = '12';
    $numpages = count($files) / $perpage;
    $page=$_REQUEST['page'];if(!$page){$page=1;}
    
    $start = $perpage * $page - $perpage;
    $end = $perpage * page;
    
    if($perpage*$page > count($files)){ $last=count($files); }else{ $last=$perpage*$page; }
    
    PHP:
    How would I go about doing that? if that is my current statement.

    Cheers!
     
    cyclotron, Jul 2, 2008 IP
  2. David Pankhurst

    David Pankhurst Member

    Messages:
    39
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #2
    What you do is create a 'key' to sort on with the data you need - file read time, and lowercase filename:

    $dir='defaultimages';
    $files=array();
    if ($handle = opendir($dir)) 
    {
      while (false !== ($file = readdir($handle))) 
      {
        if ($file != "." && $file != "css" && $file != "..") 
        {
          $date=filemtime($file);
          // create unique keyfield we can sort on - time first, unique filename after
          $keyField=$date.'-'.strtolower($file);
          $files[$keyField]=array('file'=>$file,'date'=>$date);
        }
      }
      closedir($handle);
    }
    krsort($files);
    // output
    echo '<pre>';
    foreach ($files as $file)
    {
      $date=date('r',$file['date']);
      echo "Date: ",$date," Filename: ",$file['file'],"<br />";
    }
    echo '</pre>';
    PHP:
    'krsort' sorts on the key in reverse order (so highest/newest dates come first), and the bottom part shows the results.

    The 'key' to it is preparing the array when reading in - using a custom key for each entry makes sorting easy after, and much easier to change.
     
    David Pankhurst, Jul 2, 2008 IP