开发者

Looping through directory backwards

Hay all im using a simple开发者_运维技巧 look to get file names from a dir

if ($handle = opendir('news_items/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") { 

        }
    }
}

the files are being outputted news last, oldest first.

How can i reverse this so the newest files are first?


Get the file list into an array, then array_reverse() it :)


the simplest option is to invoke a shell command

$files = explode("\n", `ls -1t`);

if, for some reason, this doesn't work, try glob() + sort()

$files = glob("*");
usort($files, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));


Pushing every files in an array whit mtime as key allow you to reverse sort that array:

<?php

$files = array();

if ($handle = opendir('news_items/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $mtime = filemtime('news_items/' . $file);

            if (!is_array($files[$mtime])) {
                $files[$mtime] = array();
            }

            array_push($files[$mtime], $file);
        }
    }
}

krsort($files);

foreach ($files as $mt=>$fi) {
    sort($fi);
    echo date ("F d Y H:i:s.", $mt) . " : " . implode($fi, ', ') . "\n";
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜