douwen8424 2012-03-12 18:28
浏览 63
已采纳

PHP和MYSQL中的新闻档案显示零结果

I am trying to list all the previous months in which posts have been made and display the number of posts, for example

2011
  November (14)
  October (12)
  April (3)
2010
  December (2)

    etc etc

The following code is how I am attempting to make this work however it doesnt actually return any results and I cannot seem to wrap my head around why.

$sql = "SELECT nid, ndate FROM weaponsnews
    ORDER BY ndate DESC";
$result = $db->query($sql);

$data = array();

while($row = $result->fetch_assoc())
{
    $year = date('Y', strtotime($row['ndate']));
    $month = date('m', strtotime($row['ndate']));

    $data[$year][$month][] = $row;
}
$result->free();

foreach($data as $_year => $_months)
{
    echo $_year. "<br>";
    foreach($_months as $_month => $_entries)
    {
        $mentries = count ($_entries);
        echo $_month. " (" .$mentries. ")";

    }
}
  • 写回答

1条回答 默认 最新

  • douhuan1937 2012-03-12 18:35
    关注

    It's easier if you do the count in the MySQL query. For example:

    SELECT YEAR(`ndate`) AS 'year', MONTH(`ndate`) AS 'month', COUNT(`nid`) AS 'count'  FROM `weaponsnews ` GROUP BY YEAR(`ndate`), MONTH(`ndate`) DESC
    

    This gives you three columns, where the first is the year, the second is the month, and the third is the number of items in that month. You can then easily iterate through this list with foreach. Something like:

    $data = array();
    while($row = $result->fetch_assoc()) {
        $data[$row['year']][$row['month']] = $row['count'];
    }
    $result->free();
    

    This should give you an array like:

    $data = array(
        '2001' => array(
            '1' => '83',
            '3' => '102'
        ),
        '2012' => array(
            '6' => '43',
            '9' => '33'
        ),
        '2013' => array(
            '7' => '55'
        )
    );
    

    You can print the tree by iterating through the array:

    foreach ($data as $year => $months) {
        echo $year.'<br>';
        foreach ($months as $month => $count) {
                echo $month.'('.$count.')<br>';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据