按照年和月计算文章后档案

时间:2014-06-25 20:48:38

标签: php mysql

我需要按照这样的年份和月份列出总的文章档案:

输出(我需要):

2014
   January(31)
   February(28)
   March(0)
   April(130)
   May(450)
   June(0)
   July(0)
   August(0)
   September(0)
   October(520)
   November(20)
   December(31)

PHP:

$sql = "SELECT title, YEAR(FROM_UNIXTIME(timestamp)) AS YEAR, 
                MONTHNAME(FROM_UNIXTIME(timestamp)) AS MONTH, 
                COUNT(*) AS TOTAL 
         FROM article GROUP BY YEAR, MONTH ORDER BY YEAR DESC, MONTH ";

$newsdata = DB->fetch($sql);

$currentYear = null;

foreach($newsdata AS $news){            
  if ($currentYear != $news['YEAR']){
     echo '<ul>'.$news['YEAR'].'</ul>';
  $currentYear = $news['YEAR'];
  } 
     echo '<li>'.$news['MONTH'].' '.$news['TOTAL'].'</li>';
  }

我的代码有效,但如果本月发布的文章只打印一个月。

输出继电器:

2014
       January(31)
       February(28)
       April(130)
       May(450)
       October(520)
       November(20)
       December(31)

我需要列出所有月份并打印每个月的总文章。如果本月未发布文章打印(0)本月。

我该如何解决我的问题?我的代码/方式是真的吗?!

1 个答案:

答案 0 :(得分:1)

您的数据库查询不会返回没有文章的月份的行。它几个月都不知道。所以你需要通过拥有所有月份的数组并循环遍历代码来处理这个问题。替代方案是更改您的架构,拥有所有12个月的另一个表,并加入其中。但我认为以下内容对您来说更容易:

$months = array( "January", "February", ...  );

然后您可以在输出中执行以下操作:

// Index article counts by month and year for easy lookup
$indexedNewsData = array();
foreach ($newsdata as $news) {
  $indexedNewsData[$news['YEAR']][$news['MONTH']] = $news['TOTAL'];
}

// Then print output
foreach($newsdata AS $news){            
  if ($currentYear != $news['YEAR']){
    echo '<ul>'.$news['YEAR'].'</ul>';
    $currentYear = $news['YEAR'];
  } else {
    // Continue here otherwise we will print each year's data 12x
    continue;
  }
  foreach ($months as $month) {
    $total = intval($indexedNewsData[$news['YEAR']][$month]);        
    echo '<li>'.$month.' '.$total.'</li>';
  }     
}