1

我有一个小的日历页面,您可以在其中单击特定月份并获取该月的所有文章。有几个月没有文章,我想避免用户点击那个月却发现它是空的部分。我如何计算一年中每个月的所有文章,然后在视图部分显示数据?

文章的数据库是这样的:

articles
id_articles -> **number**
title -> **varchar**
text -> **text**
date_created -> timestamp (CURRENT_TIMESTAMP - MM/DD/YYYY HH:MM:SS ) 

HTML 代码:

<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>
4

1 回答 1

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 标签中打印出月份名称,如果有文章,则会打印出该月作为链接以及该月的文章数量。

于 2012-12-12T00:41:13.590 回答