使用php和mysql按年和月分组存档

时间:2014-06-01 22:22:41

标签: php mysql pdo

我想创建一个这样的存档列表:

  • 2014
    • 三月
    • 二月
      • Post 1
      • Post 2
  • 2013
    • 十一月
      • Post 1

我正在使用PDO。我使用的表是将postDate作为Datetime。 postSlug用于获取干净的URL。我现在使用的编码是:

    <h1>Archives</h1>
    <hr />

    <ul>
<?php
$stmt = $db->query("SELECT postTitle, Month(postDate) as Month, Year(postDate) as Year FROM blog_posts_seo ORDER BY postDate DESC");
while($row = $stmt->fetch()){
$posts = $row['postTitle'];
$year = $row['Year'];
    $monthName = date("F", mktime(0, 0, 0, $row['Month'], 10));
    $slug = 'a-'.$row['Month'].'-'.$row['Year'];
        echo "<li>$year</li>";
    echo "<ul><li><a href='$slug'>$monthName</a></li>";

        echo "<ul><li><a href='#'>$posts</a></li></ul></ul>";
}
?>
</ul>

我得到的结果如下:

2014
    May
        Post
2013
    June
        Post
2013
    June
        Post
2012
    June
        Post

简而言之,我如何使用php对帖子和月份进行相应的分组? 我是php和mysql的初学者。因此,如果您知道解决方案,如果您可以帮助我完成编码,那将会非常有帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

那怎么样?

$data = array();
while($row = $stmt->fetch()){
  $monthName = date("F", mktime(0, 0, 0, $row['Month'], 10));     
  $data[$row['Year']][$monthName][] = array(
   'post' => $row['postTitle'],
   'slug' => 'a-'.$row['Month'].'-'.$row['Year']
  );
}
echo '<ul>';
foreach ($data as $year => $yearData){
   echo "<li>$year<br/>";
   echo '<ul>';
   foreach ($yearData as $month => $monthData){
      echo "<li>$month<br/>";
      echo '<ul>';
      foreach ($monthData as $number => $postData){
        echo "<li><a href='${postData['slug']}'>Post $number</a><br/>";
        echo "<a href='#'>${postData['post']}</a></li>";
      }
      echo '</ul></li>';
   }
   echo '</ul></li>';
}
echo '</ul>';

这个解决方案以PHP方式实现,但您也应该能够通过SQL查询获得结果,例如:

SELECT
    Year(postDate) as Year, Month(postDate) as Month,
    GROUP_CONCAT(postTitle) as posts
FROM
    blog_posts_seo
GROUP BY Year, Month
ORDER BY postDate DESC

应该将所有与年份和月份相关的帖子返回一行(未经测试),以逗号分隔。使用WITH SEPARATOR选项指定其他分隔符(请查看文档)。

文档: