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 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教