我有一个小日历页面,您可以点击特定月份并获取该月份的所有文章。有几个月没有文章,我想避免那个月用户点击的部分只发现它是空的。如何计算一年中每个月的所有文章以及后面的现有数据?
文章的数据库是这样的:
articles
id_articles -> **number**
title -> **varchar**
text -> **text**
date_created -> timestamp (CURRENT_TIMESTAMP - MM/DD/YYYY HH:MM:SS )
HTML code:
<nav id="arcive" class="clearfix">
<ul>
<li>
<a role=slide rel=2012 class="current" >2012</a>
<ul rel=2012 class="month">
<li>
<a href="#">December</a>
<a href="#">November</a>
<a href="#">October</a>
<a href="#">September</a>
<a href="#">August</a>
<a href="#">July</a>
<a href="#">Jun</a>
<a href="#">May</a>
<a href="#">April</a>
<a href="#">March</a>
<a href="#">February</a>
<a href="#">January</a>
</li>
</ul>
</li>
</ul>
</nav>
答案 0 :(得分:2)
动态创建菜单的PHP将是:
$year = '2012'; // set this to whatever the year to be queried is
$sql = 'SELECT GROUP_CONCAT(MONTH(`date_created`)) `date_created` '
. 'FROM `articles` '
. 'WHERE YEAR(`date_created`) = ' . (int) $year; // typecast for security
// run query to return list of numeric months with articles
$query = $this->db->query($sql);
$result = $query->row();
$months = explode(',', $result->date_created);
$articles_per_month = array_count_values($months); // get count of articles per each month
for ($i = 1; $i <= 12; $i++) // Loop Through 12-months
{
$month_name = date('F', mktime(0, 0, 0, $i)); // Get the name of the month from the numeric month
echo (in_array($i, $months)) // Check to see if articles for month, if so create link otherwise SPAN
? "<a href='/calendar/month/$i'>$month_name (" . $articles_per_month[$i] . ")</a>\n" // print link with number of articles
: "<span>$month_name</span>\n";
}
这将创建菜单,如果一个月没有文章将在SPAN标签内打印月份名称,如果它确实有文章将打印月份作为链接以及该月的文章数量。< / p>