PHP / MySQL组新闻/档案按年份计算

时间:2010-08-20 11:25:01

标签: php mysql

我有一些输出新闻档案边栏的代码。这一切都很好,除了它没有正确地逐月拆分这一事实。所有月份都显示所有月份,而不是将相关月份分配到其年份!很沮丧!任何帮助将不胜感激。

$query = "SELECT * FROM isnews WHERE active = '1' ORDER BY YEAR(date) DESC, MONTH(date) DESC";
$resultSet = mysql_query($query);

if (mysql_num_rows($resultSet)){
    $newsArray = array();

    echo '<ul>' . PHP_EOL;
    echo '<li><strong>Press releases:</strong></li>' . PHP_EOL;                                            

    while ($newsResult = mysql_fetch_array($resultSet)){ 
        $newDate =  $newsResult['date'] ;   
        $timePeriod = date('F  Y ',strtotime($newDate));
        $timePeriodY = date('Y',strtotime($timePeriod));
        $timePeriodM = date('F',strtotime($timePeriod));                                          

        if (!isset($newsArray[$timePeriod])){
              $newsArray[$timePeriod] = array();
        }           
        $newsArray[$timePeriod][] = $newsResult;                                      
    }                                         

    //by year
    foreach ($newsArray as $timePeriod => $newsItems){
        $timePeriodY = date('Y',strtotime($timePeriod));
        echo '<li><strong>' . $timePeriodY . '</strong>' . PHP_EOL;  
        echo '<ul>' . PHP_EOL;

        //by month
        foreach ($newsArray as $timePeriod => $newsItems){
            echo '<li><strong>' . $timePeriod . '</strong>' . PHP_EOL;  
            echo '<ul>' . PHP_EOL;                                

            //news items
            foreach ($newsItems as $item){
                echo '<li>';
                echo '<a href="'.$wwwUrl.'press-releases/'.$item["id"].'/'.$item["title"].'.php">'.$item["title"].'</a>';
                echo '</li>' . PHP_EOL;
            }     

            //end by month
            echo '</ul>' . PHP_EOL; 
            echo '</li>' . PHP_EOL;                   
        }

        //end by year
        echo '</ul>' . PHP_EOL; 
        echo '</li>' . PHP_EOL;                   
    }

    echo '<li>&nbsp;</li>' . PHP_EOL;   
    echo '</ul>' . PHP_EOL; 
} else {
    echo 'We currently have no press releases available';
}

非常感谢提前 小号

3 个答案:

答案 0 :(得分:0)

您需要使用:

ORDER BY abc, xyz DESC

答案 1 :(得分:0)

为什么你不使用

ORDER BY date DESC

答案 2 :(得分:0)

当你打印时,你为什么要重复$newsArray两次(当你在foreach中有foreach时)?

也许我错过了一些东西,但基本上每个月/每年你都会打印所有月/年的所有新闻。保持内在的foreach应该解决问题。