【问题标题】:Separate MySQL query results by month按月分隔 MySQL 查询结果
【发布时间】:2016-12-29 19:50:14
【问题描述】:

情况

我有一个 MySQL 数据库表,里面有很多日期。

现在我需要从这个表条目中创建一个表,应该如下所示:

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

等等。

代码

我现在正在尝试通过我的所有查询结果创建一个循环来执行此操作。然后我就卡住了。

我有这样的事情:

在“while”(获取关联)循环中,我有这个:

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

  $entryarray = array();

}

您可以看到,我首先将日期的月份保存到数组中。现在我不知道,如何创建数组来保存数组中每个月的所有行,最终将结果输出到表中。

【问题讨论】:

  • 显示您的查询,您可能需要GROUP BY day(datecol),month(datecol),YEAR(datecol)
  • 为什么每个月都需要表格?可以使用 datepart 在查询中直接选择特定月份。

标签: php mysql arrays


【解决方案1】:

我假设您的表格报告只有一年。如果是这样,您可以将月份用作数组的索引键。

$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
}

您现在可以通过遍历数组的键来回显$table 数组。它们将按照创建的顺序进行分组。所以这取决于你的 SQL 查询。

foreach($table as $month=>$rows)
{
     echo $month;
     foreach($rows as $row)
     {
        print_r($row);
     }
}

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    $entryarray = array();
    $stmt="";//you statement here
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                          {   
       $date = $row['pp_date'];
       $month = date('m', strtotime($date));
       $entryarray[$month][] =$row['data1'];//populate your array by the required data indexed by the month
       $entryarray[$month][] =$row['data2'];
       $entryarray[$month][] =$row['data3'];
        }
    

    然后要获取您的数据,您可以执行以下操作:

    foreach ($entryarray  as $key => $value) {
        print $key; //you will get the key of your array
        foreach ($value as $key => $value){print $value; }//the value of the required key
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多