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

时间:2012-03-12 18:28:02

标签: php mysql archive

我正在尝试列出发布帖子的所有前几个月并显示帖子数量,例如

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

    etc etc

以下代码是我试图使这项工作的方式,但它实际上并没有返回任何结果,我似乎无法理解为什么。

$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 个答案:

答案 0 :(得分:2)

如果在MySQL查询中进行计数,则会更容易。例如:

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

这为您提供了三列,其中第一列是年份,第二列是月份,第三列是该月份的项目数。然后,您可以使用foreach轻松遍历此列表。类似的东西:

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

这应该给你一个像:

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

您可以通过迭代数组来打印树:

foreach ($data as $year => $months) {
    echo $year.'<br>';
    foreach ($months as $month => $count) {
            echo $month.'('.$count.')<br>';
    }
}