dousi6192 2015-04-30 10:35
浏览 7

如何使用PHP和MySQL检索此表的分组信息?

I have a table that looks like this

Table image

the column date contains different dates in the range (2015-2009). Is it possible to use one query to retrieve data like this?

Array image

Here [2015] - is year that has an array. [01]=>'12', [01] os the month and 12 number of articles in this month i.e.

  • 写回答

2条回答 默认 最新

  • duanmeng1858 2015-04-30 13:28
    关注

    Provided the date field is actually a date, this should work:

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
    }
    
    $sql = "SELECT date_format(`date`, \"%Y-%m\") as YearMonth, count(*) as cnt " .
           "FROM someTable " .
           "GROUP BY YearMonth " .
           "ORDER BY YearMonth ";
    
    $data = array();
    
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        $currentYear = "";
        while($row = $result->fetch_assoc()) {
            $rowYear = substr($row["YearMonth"], 0, 4);
            $rowMonth = substr($row["YearMonth"], 5, 2);
            if ($rowYear != $currentYear) {
                $currentYear = $rowYear;
                $data[$currentYear] = array();
            }
            $data[$currentYear][$rowMonth] = $row["cnt"];
        }
    }
    
    $conn->close();
    
    print_r($data);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题