如何按月+年分组?

kev*_*nen 2 php mysql grouping

http://www.bioshapebenefits.nl/bioshapebenefits/en/news/donations.html

如您所见,这里有一长串条目,按日期排序,非常简单.因此,在mysql中,只有列'name'和'date',例如.如果我想用php创建一个列表,这也很简单,只需按日期排序.

但是,我如何将月份和年份放在两者之间,如示例所示?喜欢:

2010年6月

  • TRALA
  • 拉拉
  • 瓦剌

2010年5月

  • TRALA
  • 拉拉
  • 瓦剌

Pau*_*eld 5

在SQL Server中,它将如下所示,我想想mysql有类似的东西:

GROUP BY Year(Date), Month(Date)


Pet*_*ley 5

有十几种方法来修饰这只猫,但我的方法可能就是这样(所有粗略的代码片段,而不是完整的实现)

一,查询

select `name`
     , month(`date`) as date_month
     , year(`date`) as date_year
  from [Table]
 order by `date` desc
Run Code Online (Sandbox Code Playgroud)

然后,将数据组织到所需的逻辑组中

$templateData = array();
foreach ( $rows as $row )
{
  $templateData[$row->date_year][$row->date_month][] = $row->name;
}
Run Code Online (Sandbox Code Playgroud)

然后,在模板中

<?php foreach ( $templateData as $year => $months ) : ?>
  <?php foreach ( $months as $month => $names ) : ?>
    <h2><?php echo $month, ' ', $year; ?></h2>
    <ul>
      <?php foreach ( $names as $name ) : ?>
        <li><?php echo $name; ?></li>
      <?php endforeach; ?>
    </ul>
  <?php endforeach; ?>
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)