为HighCharts格式化正确的JSON格式的PHP / MySQL数据

时间:2013-02-18 05:40:05

标签: php mysql json highcharts

我已经把头发拉了几天试图将一些数据组织成适当的JSON格式,以便可以在HighCharts图中绘制。

我的计划是执行一个jQuery函数来调用PHP脚本,该脚本从MySQL数据库中提取几列天气数据。我可以重新编写JavaScript方面的数据,但是希望在PHP中完成所有数据组织,然后将一个正确的JSON结构导入HighCharts引擎。

我正在查看天气数据,因此我每分钟都会抽取几列数据。我从MySQL检索的数据列是:JSTimestamp(这是JavaScript的unix时间戳* 1000),avgOutdoorTemperature,avgIndoorTemperature,avgOutdoorHumidity,avgIndoorHumidity。我已经在他们自己的数组中填充了这些列中的每一列。

我似乎无法绕过将数据操作为以下JSON /数组格式所需的PHP逻辑:

[
  [
    [JSTimestamp1, avgOutdoorTemperature1],
    [JSTimestamp2, avgOutdoorTemperature2],
    [JSTimestamp3, avgOutdoorTemperature3],
    [JSTimestampN, avgOutdoorTemperatureN]
  ],
  [
    [JSTimestamp1, avgIndoorTemperature1],
    [JSTimestamp2, avgIndoorTemperature2],
    [JSTimestamp3, avgIndoorTemperature3],
    [JSTimestampN, avgIndoorTemperatureN]
  ],
  [
    [JSTimestamp1, avgOutdoorHumidity1],
    [JSTimestamp2, avgOutdoorHumidity2],
    [JSTimestamp3, avgOutdoorHumidity3],
    [JSTimestampN, avgOutdoorHumidityN]
  ],
  [
    [JSTimestamp1, avgIndoorHumidity1],
    [JSTimestamp2, avgIndoorHumidity2],
    [JSTimestamp3, avgIndoorHumidity3],
    [JSTimestampN, avgIndoorHumidityN]
  ]
]

我用虚拟数据填充了上面的结构,它在HighCharts中绘制得很漂亮。这是一个示例演示,展示了图形的外观:http://highcharts.com/jsbin/afutef/11/edit#javascript,live

我目前的代码是:

<?php

include_once('./include/mysqldatabase.php');
include_once('./include/mysqlresultset.php');

date_default_timezone_set('America/New_York');

$MYSQL_HOST = 'ip_address';
$MYSQL_USER = 'username';
$MYSQL_PASS = 'password';
$MYSQL_NAME = 'weatherdata';

$db = MySqlDatabase::getInstance();
try {
    $conn = $db->connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASS, $MYSQL_NAME);
}
catch (Exception $e) {
    die($e->getMessage());
}

$query = "
    select
        RecDate,
        unix_timestamp(RecDateTime)*1000 as JSTime,
        avgOutdoorTemperature,
        avgIndoorTemperature,
        avgOutdoorHumidity,
        avgIndoorHumidity
    from `rollup-minute-60`
    where 
        RecDate > 201301010000
    ";

$timeArray = array();
$avgOutdoorTemperatureArray = array();
$avgIndoorTemperatureArray = array();
$combinedArray = array();
$i = 0;

$seriesNames = array('Average Outdoor Temperature','Average Indoor Temperature', 'Average Outdoor Humidity', 'Average Indoor Humidity');

foreach ($db->iterate($query) as $r) {
    $jstime = $r->JSTime;
    $avgOutdoorTemperature = $r->avgOutdoorTemperature;
    $avgIndoorTemperature = $r->avgIndoorTemperature;
    $avgOutdoorHumidity = $r->avgOutdoorHumidity;
    $avgIndoorHumidity = $r->avgIndoorHumidity;

    $timeArray[$i] = (float)$jstime;
    $avgOutdoorTemperatureArray[$i] = (float)$avgOutdoorTemperature;
    $avgIndoorTemperatureArray[$i] = (float)$avgIndoorTemperature;
    $avgOutdoorHumidityArray[$i] = (float)$avgOutdoorHumidity;
    $avgIndoorHumidityArray[$i] = (float)$avgIndoorHumidity;    

    $combinedArray[$i] = array((float)$avgOutdoorTemperature, (float)$avgIndoorTemperature, (float)$avgOutdoorHumidity, (float)$avgIndoorHumidity);

    $i++;
}

echo "Combined array:<br>";
echo json_encode($combinedArray);
echo "<br><br><br>";

echo "Time array:<br>";
echo json_encode($timeArray);
echo "<br><br><br>";

$arraySize = sizeof($timeArray);
$seriesNameSize = sizeof($seriesNames);
$outputJSONArray = array();
$tempArray = array();

for ($i=0; $i<$seriesNameSize; $i++) {

    for ($j=0; $j<$arraySize; $j++) {
        $tempArray = array();

        array_push($tempArray, $timeArray[$j], $combinedArray[$j][$i]);
        echo "i=".$i.", j=".$j.", tempArray: " . json_encode($tempArray) ."<br>";

        $outputJSONArray[$i] = $tempArray;

     } 
}

echo json_encode($outputJSONArray);

?>

使用上面的当前代码,我的输出数组只显示$ outputJSONArray中的最后一个元素而不是多维构造。

任何人都可以帮我指出正确的方向吗?我在这个网站上找到了很多很好的信息,以帮助我开始,但需要一些帮助来克服最后的障碍。

谢谢!

2 个答案:

答案 0 :(得分:1)

检查Highcharts常见问题解答:http://docs.highcharts.com/#preprocessing-data-from-a-database 第二个例子告诉你如何做到这一点:

<?php
while ($row = mysql_fetch_array($result)) {
   extract $row;
   $datetime *= 1000; // convert from Unix timestamp to JavaScript time
   $data[] = "[$datetime, $value]";
}
?>
var chart = new Highcharts.Chart({
      chart: {
         renderTo: 'container'
      },
      series: [{
         data: [<?php echo join($data, ',') ?>]
      }]
});

答案 1 :(得分:0)

感谢您回复Paweł。我一直在使用您发布的示例,并且对单个时间序列非常了解。然而,我对多个系列的正确格式化感到困惑。

我努力操纵PHP端的数据以正确的格式获取数据:

[
  [
    [time1, y1],
    [time2, y2],
    [time3, y3]
  ]
  [
    [time1, z1],
    [time2, z2],
    [time3, z3]
  ]
  [
    ...
  ]
]

然而,在今天早些时候玩完东西并最终在白板上绘制解决方案后,我发现了一个似乎有效的解决方案,并要求我为每个系列遍历收集的数据阵列一次。它可能不是最佳的,但适用于我测试的几千点。这是我的参考代码:

$seriesNames = array('Average Outdoor Temperature','Average Indoor Temperature');

foreach ($db->iterate($query) as $r) {
    $time = (float)$r->RecDateTime;
    $jstime = (float)($r->Timestamp*1000);
    $avgOutdoorTemperature = (float)$r->avgOutdoorTemperature;
    $avgIndoorTemperature = (float)$r->avgIndoorTemperature;

    $dataArray[] = array(array($jstime, $avgOutdoorTemperature), array($jstime, $avgIndoorTemperature));
}

$arraySize = sizeof($dataArray);
$seriesNameSize = sizeof($seriesNames);

for ($i=0; $i<$seriesNameSize; $i++) {
    $tempArray = array();
        for ($j=0; $j<$arraySize; $j++) {
            $tempArray[] = $dataArray[$j][$i];  
        } 
    $outputJSONArray[] = $tempArray;
}

echo json_encode($outputJSONArray);

我想我可以执行多个查询并手动添加每个系列,但我最终打算使用的查询相当密集,并且更愿意只调用一次。