grouping archive by year and month using php and mysql

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

I want to create an archive list like this:

  • 2014
    • March
    • Feb
    • Jan
      • Post 1
      • Post 2
  • 2013
    • November
      • Post 1

I am using by PDO. the table I m using is having postDate as Datetime. postSlug is used to get a clean url. The coding I am using now is:

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

The result im getting is as follows:

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

In short how do I group the posts and months accordingly using php? I am am beginner in php and mysql. Therefore it would be of great help if you can help me in the complete coding if you know the solution. Thanks!

回答1:

How about that?

$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>'; 

This solution does it the PHP way, but you should be able to get the result with a SQL query too, with something like:

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 

which should return all the posts related by year and month in a single row (not tested), separated by commas. Use the WITH SEPARATOR option to specify a different separator (check the doc).

Documentation:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!