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 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大