写博客和使用文件I / O输入的最新日期首先


writing a blog and using file i/o input by newest date first?

<?php
foreach (glob("POSTS/*.txt") as $filename) 
        {       
            $file = fopen($filename, 'r') or exit("Unable to open file!");
            //Output a line of the file until the end is reached

                echo date('D, M jS, Y H:i a', filemtime($filename))."<br>";
                echo '<h2>' . htmlspecialchars(fgets($file)) . '</h2>';
                while(!feof($file))
                  {
                  echo fgets($file). "<br>";
                  }
            echo "<hr/>";
        }
    fclose($file);

    ?>

我正在写一个博客,已经能够输入文件,但只能从最旧的文件开始

我如何使它,以便我输入他们的最新日期第一?

谢谢

使用usort()将文件数组按正确的顺序排列(日期desc)。

function timeSort($first, $second) {
    $firsttime = filemtime($first);
    $secondtime = filemtime($second);
    return $secondtime - $firsttime;
}
$files = glob("POSTS/*.txt");
usort($files, 'timeSort');
foreach ($files as $filename) {
     /* Same as before */
}

如果您真的坚持使用文本文件而不是数据库来存储您的博客条目,那么按照所需的方式对它们进行排序的一种简单方法是使用array_reverse(),如下所示:

$posts = array_reverse(glob("POSTS/*.txt"));
foreach($posts as $filename) {
    // do your stuff
}