在PHP中,如何檢索包含到通過創建時間排序的文件夾中的文件(或其他任何排序機制)?
According to the doc,所述READDIR()函數:
的文件名,在其中它們被 文件系統存儲在 順序返回。
在PHP中,如何檢索包含到通過創建時間排序的文件夾中的文件(或其他任何排序機制)?
According to the doc,所述READDIR()函數:
的文件名,在其中它們被 文件系統存儲在 順序返回。
保存自己的信息到一個數組,數組
if($h = opendir($dir)) {
$files = array();
while(($file = readdir($h) !== FALSE)
$files[] = stat($file);
// do the sort
usort($files, 'your_sorting_function');
// do something with the files
foreach($files as $file) {
echo htmlspecialchars($file);
}
}
嘿排序的數組,然後循環,甚至不是很大DirectoryIterator能做到開箱即用。嘆。
似乎有一個非常強大的腳本來完成這裏引用的所有內容:preg_find。我從來沒有使用它,但它看起來不錯。
sorted in by filesize, in descending order?
$files = preg_find('/./', $dir,
PREG_FIND_RECURSIVE| PREG_FIND_RETURNASSOC |
PREG_FIND_SORTFILESIZE|PREG_FIND_SORTDESC);
$files=array_keys($files);
你可以使用scandir()
讀取目錄的內容到一個數組,然後使用fileatime()
或filectime()
看到每個文件的訪問或創建時間,分別。從這裏排序數組不應該太難。
您可以將文件存儲在數組中,其中鍵爲文件名,值爲要排序的值(即創建日期),並在該陣列上使用asort()
。
$files = array(
'file1.txt' => 1267,
'file3.txt' => 1267011892,
'file2.txt' => 1266971321,
);
asort($files);
var_dump(array_keys($files));
# Output:
array(3) {
[0]=>
string(9) "file2.txt"
[1]=>
string(9) "file3.txt"
[2]=>
string(9) "file1.txt"
}
使用shell_exec在os級執行命令?在linux/unix盒子上這可能會工作;
$output=shell_exec('ls -t1');
這是我的解決方案:
$fileList = array();
$files = glob('home/dir/*.txt');
foreach ($files as $file) {
$fileList[filemtime($file)] = $file;
}
ksort($fileList);
$fileList = array_reverse($fileList, TRUE);
print_r($filelist);
輸出是這樣的:然後用 「foreach」 循環
array(
(int) 1340625301 => '/home/dir/file15462.txt',
(int) 1340516112 => '/home/dir/file165567.txt',
(int) 1340401114 => '/home/dir/file16767.txt'
)
把你需要的文件。
...請不要。 – knittl 2010-02-24 12:22:57