2010-03-11 49 views

回答

14
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 />'; 
} 

貸記goes here

+0

@stereofrog:好點,謝謝(編輯答案) – ChristopheD

+0

好的解決方案,但它不會擴展。 –

1

一個解決辦法是:

  • 遍歷該目錄中的文件 - 使用DirectoryIterator,例如
  • 對於每個文件,得到其最後修改時間,使用SplFileInfo::getMTime
  • 將所有這些放在一個數組中:
    • 文件名作爲關鍵字
    • 修改倍值
  • 和數組排序,無論使用哪種asortarsort - 這取決於您要在其中文件的順序。


例如,這部分程序:

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

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

給我:

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 

即在我的腳本保存在目錄中的文件列表,用最最近在名單的開頭進行了修改。

3

通過使用readdir將數組連同filemtime保存在一個目錄中讀取目錄中的文件。根據此值對數組進行排序,然後獲得結果。