gpt4 book ai didi

php - 使用 PHP 计算年月存档中的内容

转载 作者:行者123 更新时间:2023-11-29 08:14:11 26 4
gpt4 key购买 nike

我需要打印每年/月的新闻数量,如下所示:

2013

  • 十月 (20)
  • 十一月 (45)
  • 九月(80)

2014

  • 一月 (5)

我有这个:

 $sql = "SELECT YEAR(FROM_UNIXTIME(timestamp)) AS YEAR, 
MONTHNAME(FROM_UNIXTIME(timestamp)) AS MONTH,
COUNT(*) AS TOTAL
FROM NEWS GROUP BY YEAR, MONTH";
$newsdata = DataAccess::ArrayFetch($sql);

foreach($newsdata AS $news){
//what???
}

现在,如何打印年份和月份?

最佳答案

您在查询中对它们进行排序,然后按该顺序打印它们。您需要检测年份更改,以打印年份标题:

$sql = "SELECT YEAR(FROM_UNIXTIME(timestamp)) AS YEAR, 
MONTHNAME(FROM_UNIXTIME(timestamp)) AS MONTH,
COUNT(*) AS TOTAL
FROM NEWS GROUP BY YEAR, MONTH ORDER BY YEAR DESC, MONTH ";
$newsdata = DataAccess::ArrayFetch($sql);

$currentYear = null;

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

关于php - 使用 PHP 计算年月存档中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20938179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com