简体   繁体   中英

PHP: ordered directory listing

How to list files in a directory in "last modified date" order? (PHP5 on Linux)

function newest($a, $b) 
{ 
    return filemtime($a) - filemtime($b); 
} 

$dir = glob('files/*'); // put all files in an array 
uasort($dir, "newest"); // sort the array by calling newest() 

foreach($dir as $file) 
{ 
    echo basename($file).'<br />'; 
} 

Credit goes here .

read files in a directory by using readdir to an array along with their filemtime saved. Sort the array based on this value, and you get the results.

A solution would be to :

  • Iterate over the files in the directory -- using DirectoryIterator , for instance
  • For each file, get its last modification time, using SplFileInfo::getMTime
  • Put all that in an array, with :
    • the files names as keys
    • The modification times as values
  • And sort the array, with either asort or arsort -- depending on the order in which you want your files.


For example, this portion of code :

$files = array();
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        $files[$fileinfo->getFilename()] = $fileinfo->getMtime();
    }
}

arsort($files);
var_dump($files);

Gives me :

array
  'temp.php' => int 1268342782
  'temp-2.php' => int 1268173222
  'test-phpdoc' => int 1268113042
  'notes.txt' => int 1267772039
  'articles' => int 1267379193
  'test.sh' => int 1266951264
  'zend-server' => int 1266170857
  'test-phing-1' => int 1264333265
  'gmaps' => int 1264333265
  'so.php' => int 1264333262
  'prepend.php' => int 1264333262
  'test-curl.php' => int 1264333260
  '.htaccess' => int 1264333259

ie the list of files in the directory where my script is saved, with the most recently modified at the beginning of the list.

Try that same query on google and you'll get answers faster. Cheers. http://php.net/manual/en/function.filemtime.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM