php - 按年月归档

标签 php mysql datetime group-by archive

我正在尝试构建年\月存档。

它拒绝输出我想要的东西,所以我希望你们中的一个人能把我推向正确的方向。

我想按年份排序,并显示每年的月份(如果存在)并像这样输出:

2012
 - June
 - August 
2011
 - July

我的代码是这样的:

$query = "SELECT * FROM article WHERE full_name ='$safe_name' group by year, month";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$year = $row['year'];
$month = $row['month'];
echo "<ul class='year'><li><a>{$year}</a>";
echo "<ul class='months'><li><a>{$month}</a></li></ul>
</li></ul>";
}

但它输出:

2012
 - june

2012
 - august

2011
 - july

当我只按年份分组时,它会输出:

2012
 - june
2011
 - july

我有一个“date_posted”行,它是日期时间 (yyyy-mm-dd 00:00:00)。 最重要的是,我有 1 行代表月份,1 行代表年份(我知道这很愚蠢,但我不知道如何通过使用“date_posted”行来做到这一点。

我阅读了一些关于这个主题的帖子,但它对我没有用。 非常感谢任何帮助!

最佳答案

这应该有效。获取结果时,有时可以很方便地对其进行重组,以便在迭代 View 时轻松使用。

$query = "SELECT * FROM article WHERE full_name ='$safe_name' group by year, month";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result)) {

   // Get data
   $year = $row['year'];
   $month = $row['month']

   // Structure it
   $archive[$year][] = $month;

}

// Display data
foreach($archive as $year => $months)
{
   // Show year
   echo "<ul class='year'><li><a>{$year}</a>";

   // Month container
   echo "<ul class='months'>"

   // Get months
   foreach($months as $month)
   {
     echo("<li><a>{$month}</a></li>"; 
   }

   // Close Month/Year containers
   echo("</ul></li></ul>");
}

关于php - 按年月归档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11781012/

相关文章:

sql-server - 使用 T-SQL 获取日期时间的时间

python Pandas : How do I apply a function requiring an extended class (datetime)?

php - Google Chrome 和流式 HTTP 连接?

php - 准备语句 INSERT INTO xxx () VALUES (), (), (), ... 可变数量的记录?

php - 在浏览器中使用 PHP 脚本运行 composer

php - 帐户搜索通配符 - SugarCRM

php - 警告 : move_uploaded_file(upload/200. jpg):无法打开流

php - 插入多个复选框选择的值

PHP/MySQL 性能问题

python - 在 python 中处理国际日期