donglu9872 2015-03-06 19:37
浏览 110
已采纳

如何从星期一到星期日将数据分组为几周

I'm displaying some database user statistics from my mySQL table. I want to group the data by weeks so I can have individual tables for each week, Monday to Sunday. The dates in the database are stored as YYYY-MM-DD.

Currently I have the following PHP to access the data:

try {
        $sql   = "SELECT * 
                  FROM metric  
                  WHERE userid='".$tuserid."';";
        $result = $pdo->query($sql);
    }
    catch (PDOException $e) {
        $error =  $e->getMessage();
        include $errorpage;
        exit();
    }
    while ($row = $result->fetch()) {
                $metrics[] = array(
                    'id' => $row['id'],
                    'date' => $row['date'],
                    'value1' => $row['value1'],
                    'value2' => $row['value2'],
                     'value3' => $row['value3'],
                     'value4' => $row['value4']
        );
    }

And then I output it with this:

<table border="1" cellpadding="2px">
 <thead>
      <tr>
          <th bgcolor="#CECECE">Date</th>
          <th bgcolor="#CECECE">Candidates Added</th>
          <th bgcolor="#CECECE">Candidates Edited</th>
          <th bgcolor="#CECECE">Notes Added</th>
          <th bgcolor="#CECECE">Candidates Forwarded</th>
      </tr>
   </thead>
   <tbody>
<?php   
    for ($i=0;$i<count($metrics);$i++){
    ?>
    <tr>
          <td><center><?php echo $metrics[$i]['date'] ?></center></td>
          <td><center><?php echo $metrics[$i]['value1'] ?></center></td>
          <td><center><?php echo $metrics[$i]['value2'] ?></center></td>
          <td><center><?php echo $metrics[$i]['value3'] ?></center></td>
          <td><center><?php echo $metrics[$i]['value4'] ?></center></td>
  </tr>

<?php   
    }
?>
</tbody>
</table>

And here's an example of the output:

enter image description here

How can I separate the data into weeks starting from Monday to Sunday?

  • 写回答

1条回答 默认 最新

  • dongtang1966 2015-03-06 19:49
    关注

    Add DAYOFWEEK() to your query:

    $sql   = "SELECT *, DAYOFWEEK(date_field) as DWNum
                FROM metric  
                WHERE userid='".$tuserid."';";
    

    And add that where you put the fields in the $metrics array.

    As you loop through and build the table:

    if($metrics[$i]['DWNum']==1) //1=Sunday
    {
       echo "<tr><td colspan='5'>NEW WEEK</td></tr>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计