我的新闻脚本无法按正确的顺序组织新闻


My news script wont organize news by the right order

因此,读取日期并按正确顺序排序基本上存在问题。我不知道为什么,但它有时会显示今天的日期。你们有人能清理代码吗?我认为它太乱了,我对php不是很好。

基本上,新闻脚本是这样的:它从includes/news文件夹中读取,该文件夹包含新闻的.txt文件。每个新闻文件都有一个这样的名称:CCD_ 1,它需要从最新到最老(最新向上,最老向下),即按逆时间顺序排列。

感谢您为我们提供帮助。

<?
$files = array();
if($handle = opendir( 'includes/news' )) {
    while( $file = readdir( $handle )) {
        if ($file != '.' && $file != '..') {
            // let's check for txt extension
            $extension = substr($file, -3);
            // filename without '.txt'
            $filename = substr($file, 0, -4);
            if ($extension == 'txt')
                $files[] = $filename; // or $filename
        }
    }
    closedir($handle);
}
rsort($files);
foreach ($files as $file)
{
    // get post date
    $postdate = substr($file, 0, 10);
    $postdate = str_replace(array('[', ']'), '', $postdate);
    $todaysdate = date("d.m.y");
    if($postdate == $todaysdate) { $fromtoday = "true"; }
    $postdate = date('F jS, Y', strtotime($postdate));
    $filetitle  = substr($file, 10);
    if($fromtoday == "true") { echo "<b style='"color: #ffb400;'">&#8987; NEW:</b>"; }
    echo '<a href="?module=news&read=' . $file . '"><span style="float:right;">' . $postdate . '</span>' . $filetitle . "</a>";
}
?>

您的最佳选择可能是使用usort()

bool usort ( array &$array , callable $value_compare_func )

您必须为比较($value_compare_func)创建一个函数,该函数将解析字符串中的日期,并对它们进行比较。最好查看文档中的示例。

你会这样使用它:

usort($files, function($a, $b) {
        // here is the comparison logic
        // return -1,0 or 1
});

通过这种方式,您可以根据使用正则表达式从字符串(或其他任何内容)中解析的日期进行排序。

要实现相反的顺序,只需在排序函数中交换-1和1。