dongwu8050 2014-09-22 14:11
浏览 24
已采纳

按月分隔MySQL查询结果

The situation

I have a MySQL Database Table with many dates in it.

Now I need to create a table from this tableentries which should look like this:

May        |          |
22.05.2014 | Person 1 | Person 2
23.05.2014 | Person 1 | Person 2

June       |          |
02.06.2014 | Person 1 | Person 2
25.06.2014 | Person 1 | Person 2

etc..

The code

I am now trying to create a loop through all my query results to do so. And right there I stuck.

I am having something like this:

In the "while" (fetch assoc) loop I have this:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  $date = $row['pp_date'];
  $month = date('m', strtotime($date));

  $entryarray = array();

}

You can see, that I first save the month of the date into the array. And now I don't know, how to create the array to hold all rows for each month in the array to finally output the result into the table.

  • 写回答

2条回答 默认 最新

  • douzhantao2857 2014-09-22 14:18
    关注

    I assume your table report is for just one year. If so, you can just use the month as an index key on an array.

    $table = array();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $month = date('m', strtotime($row['pp_date']));
      if(!isset($table[$month]))
      {
         $table[$month] = array();
      }
    
      $table[$month][] = $row; //... add a table row
    }
    

    You can now echo the $table array by iterating over the keys of the array. They will be grouped in the order they were created. So that depends upon your SQL query.

    foreach($table as $month=>$rows)
    {
         echo $month;
         foreach($rows as $row)
         {
            print_r($row);
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘