user1796164
user1796164

Reputation: 131

how to folder sort out by time php

how to folder sortout by time example i create last/latest folder in directory so last folder show on top.

here is code to show directory only

<?php

function folderlist(){
  $startdir = './';
  $ignoredDirectory[] = '.'; 
  $ignoredDirectory[] = '..';
   if (is_dir($startdir)){
       if ($dh = opendir($startdir)){
           while (($folder = readdir($dh)) !== false){
               if (!(array_search($folder,$ignoredDirectory) > -1)){
                 if (filetype($startdir . $folder) == "dir"){
                       $directorylist[$startdir . $folder]['name'] = $folder;
                       $directorylist[$startdir . $folder]['path'] = $startdir;
                   }
               }
           }
           closedir($dh);
       }
   }
return($directorylist);
}


$folders = folderlist();
    foreach ($folders as $folder){
    $path = $folder['path'];
    $name = $folder['name'];

echo '<li><a href="' .$path .'index.php?album=' .$name . '" class="style1"><font face="Tahoma" class="ws10"><B>' . $name . '</B></a><br /></li>';
  }
?>

Upvotes: 0

Views: 141

Answers (1)

duellsy
duellsy

Reputation: 8577

To do that, you'll need to first grab the created time for the folder, and add that as the start of the key for the array item, then you'll be able to sort based on the key... something like this

<?php
function folderlist(){
  $directorylist = array();
  $startdir = './';
  $ignoredDirectory[] = '.';
  $ignoredDirectory[] = '..';
   if (is_dir($startdir)){
       if ($dh = opendir($startdir)){
           while (($folder = readdir($dh)) !== false){
               if (!(array_search($folder,$ignoredDirectory) > -1)){
                 if (filetype($startdir . $folder) == "dir"){
                       $created = filectime($startdir . $folder);
                       $directorylist[$created . $startdir . $folder]['name'] = $folder;
                       $directorylist[$created . $startdir . $folder]['path'] = $startdir;
                   }
               }
           }
           closedir($dh);
       }
   }

  ksort($directorylist);
  return($directorylist);
}


$folders = folderlist();

$total_files = 0;
foreach ($folders as $folder){
    $path = $folder['path'];
    $name = $folder['name'];
    $count = iterator_count(new DirectoryIterator($path . $name));
    $total_files += $count;

    echo '<li>';
    echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
    echo '<strong>' . $name . '</strong>';
    echo ' (' . $count . ' files found)';
    echo '</a>';
    echo '</li>';
}
  echo "Total Files:". $total_files;
?>

Note the new $created variable in use, and also the ksort() method being used to sort the array by its key.

You could sort in reverse order ising krsort.

You could also change the ordering to be based on the modified date, by using filemtime() instead of filectime()

Upvotes: 1

Related Questions