MySQL 使用 PHP 和 Group Concat 输出到 JSON



我正在尝试将我的家庭温度表输出为json格式。当仅使用 WHERE 使用一个位置时,我已经成功地输出到 json,但我似乎无法正确输出代码并按位置对其进行分组,如下例所示。

使用包含如下数据的大型 mysql 表

 --------------------------------------
|timeof              |temp   |location |
|--------------------------------------|
|2013-09-30 00:46:45 | 10.34 | outside |
|2013-09-30 00:43:45 | 18.34 | kitchen |
|2013-09-30 00:41:45 | 11.34 | outside |
|2013-09-30 00:42:34 | 19.34 | lounge  |
|2013-09-30 00:41:45 | 11.34 | outside |
|.....

然后使用以下PHP代码和MySQL查询,我相信我使用的是正确的查询,但是我的JSON格式一团糟!

$fetch= mysql_query("
Select
  location,
  Group_Concat(timeof,temp)
From                              
  temperatures
Group By
  location
");
$result = array($name => array());
while ($row = mysql_fetch_assoc($fetch))
$result[$location][] = $row;
echo json_encode($result);

上面的代码正在生成此 JSON 输出,但它不是我需要的方式;

{"":[{"location":"outside","Group_Concat(timeof,temp)":"2013-08-03 
04:51:5619.31,2013-07-23 14:51:5221.63,2013-08-03 09:51:5421.06,2013-07-23 
19:51:5122.00,2013-08-03 14:51:5222.69,2013-07-24 00:51:4921.31,2013-08-03 
16:03:0021.69,2013-08-06 07:51:2616.44,2013-07-14 20:45:2322.75,2013-07-26 
16:52:4118.38,2013-07-15 01:27:4622.38,2013-08-06 12:51:2416.56,2013-07-26"},
{"location":"kitchen","Group_Concat(timeof,message)":"2013-07-23 11:52:3017.31,
2013-09-29 18:50:3319.63,2013-08-25 01:07:1217.13,2013-10-22 11:14:3217.06,
2013-08-03 06:52:3114.44,2013-08-14 00:30:3417.31,2013-09-04 20:09:5921.13,2013-09-18 

这就是我真正需要 JSON 输出出现的方式;

[{name: location,data: [ [timeof, temp],[timeof, temp],[timeof, temp] ]}, {name: location,data: [ [timeof, temp],[timeof, temp],[timeof, temp] ]}]

知道我需要更改什么才能获得正确的输出吗?

您不应该使用 mysql_,因为 lib 已被弃用。此外,您的代码风格也可以改进。

但无论如何,解决方案是:

// Use an ALIAS (AS) for the GROUP_CONCAT:
$fetch= mysql_query("
Select
  location,
  Group_Concat(timeof,temp) AS data
From                              
  temperatures
Group By
  location
");
$result = array();
while ($row = mysql_fetch_assoc($fetch)) {
    // GROUP_CONCAT uses a comma as default seperator,
    // turn it back into an array:
    $row['data'] = explode(',', $row['data']);
    // Porper array dimensions:
    $result[] = array('name' => $row['location'], 'data' => $row['data']);
}
echo json_encode($result);

为什么要在 SQL 层聚合数据,然后解聚以写入 JSON ?

如果是我,我会做这样的事情。

 $qry="SELECT location, timeof, temp
    FROM termperatures
    ORDER BY location, timeof";
 ...
 $data=array();
 $x=0;
 $locn='';
 while ($r=mysqli_fetch_asoc($result)) {
       if ($r['location']!=$locn) {
          $x++;
          $data[$x]=array(
              'name'=>$r['location',
              'data'=>array()
              );
          $locn=$r['location'];
       }
       $data[$x]['data'][]=array($r['timeof'], $r['temp']);
 }
 print json_encode($data);

可以在此之上固定FSM,将JSON编写为流,而不是将其作为数据报处理以减轻内存压力。

最新更新