【发布时间】:2012-03-04 09:57:45
【问题描述】:
我刚开始使用 PHP 和 mySQL,我正在创建某种博客。有时我认为它进展顺利 - 我的档案代码遇到了一些问题。
我认为解决方案会很简单,但我太盲目了,我自己找不到重点。
这是我的实际代码,一切正常,链接也是:
$sql = mysql_query ("SELECT YEAR(date) AS get_year, MONTH(date) AS get_month, COUNT(*) AS entries FROM blogdata GROUP BY get_month ORDER BY date ASC") or die('No response from database.');
while ($row = mysql_fetch_array($sql)) {
$get_year = $row["get_year"];
$get_month = $row["get_month"];
$entries = $row["entries"];
// get month name
$this_month = date( 'F', mktime(0, 0, 0, $row["get_month"]) );
echo '<dl>';
echo '<dt>Entries from '. $get_year . '</dt>';
echo '<dd><a href="archives.php?month='. $get_month .'">Entries from '. $this_month . ' </a>(' . $entries . ')</dd>';
echo '</dl>';
}
好的。然后在浏览器中的结果看起来是这样的:
- 2012 年的参赛作品
- 1 月 (2) 月的参赛作品
- 2012 年的参赛作品
- 2 月的参赛作品 (1)
现在我的问题是:如何恢复一年中的所有月份?像这样:
- 2012 年的参赛作品
- 1 月 (2) 月的参赛作品
- 2 月的参赛作品 (1)
我害怕创建一个 12 个月的数组,因为可能不是每个月都会有条目,而且我不想显示空月份。
有人可以帮助我吗?谢谢!!
---------------
在这里,我再次展示您友好帮助的最终(工作!!)结果:
至少,我使用了 Sam 的版本,因为它正是我想要的。我真的很感谢其他答案 - 特别是因为现在我有更多的东西要考虑下一次尝试。
Sam 的代码工作得非常棒......我唯一遇到的问题是,在使用数组后,它只打印出 'December' 作为几个月。
于是我再次查看了代码,经过 2 个小时的寻找和尝试,我发现了问题所在。它嵌套在以下行中:
$this_month = date( 'F', mktime(0, 0, 0, $row['get_month']) );
将其更改为:
$this_month = date( 'F', mktime(0, 0, 0, $month['get_month']) );
现在一切正常。正是我所期望的。所以这是工作的最终代码:
$sql = mysql_query ("SELECT YEAR(date) AS get_year, MONTH(date) AS get_month, COUNT(*) AS entries FROM blogdata GROUP BY get_year, get_month ORDER BY date ASC") or die('No response from database.');
$entries = array();
while ($row = mysql_fetch_assoc($sql)) {
$entries[$row['get_year']][] = $row;
}
foreach($entries as $year => $months) {
echo '<dl>';
echo '<dt>Entries from '. $year . '</dt>';
foreach($months as $month) {
$this_month = date( 'F', mktime(0, 0, 0, $month['get_month']) );
echo '<dd><a href="archives.php?month='. $month['get_month'] .'">Entries from '. $this_month . ' </a>(' . $month['entries'] . ')</dd>';
}
echo '</dl>';
}
再次感谢大家!
【问题讨论】:
标签: php mysql date loops blogs