绘制从JSON php导入到Highcharts的多个系列

时间:2016-04-21 13:48:48

标签: php mysql json highcharts

因为我对JS很新,我无法理解如何在我的代码中实现多个数据系列

这是我用作数据抓取器的php页面:

getTrendData-TIMEREQUESTED-hms.php

<?php
    //Define possible Argument request
    $format = $_GET['format'];

    if($format=='json')    {
        header("Content-type: text/json");
    }

    //Define database credential
    $servername = "localhost";
    $username   = "test";
    $password   = "test";
    $dbname     = "test";
    try {
        //Open connection to mysql_db from defined Database credentials
        $connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
        $sql   = "select TIMEREQUESTED,TS FROM TIMEREQUESTED ORDER BY TS;";
        $result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
        //create an array
        $data = array();
        while($row = mysqli_fetch_assoc($result))    {
            $TIMEREQUESTED = strtotime($row['TIMEREQUESTED'])*1000;
            $TS = strtotime($row['TS'])*1000;
            $data[] = array($TS, $TIMEREQUESTED);
        }

        echo json_encode($data);
        //close the db connection
        mysqli_close($connection);
    }

    catch(PDOException $e)  {
        echo $e->getMessage();
    }

    ?>

比我在HighCharts中包含一个Ajax调用,每次调用2500毫秒,

getTrendData-TIMEREQUESTED-hms.php

[[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0],[1461242303000,26.25,0],[1461242835000,-2.5,0],[1461242869000,-2.5,0],[1461242991000,1.5,0],[1461243034000,3.14,0],[1461243374000,-14.22,0],[1461243456000,-11.92,0],[1461244995000,0,0],[1461245036000,-3.6,140],[1461245208000,-3,140],[1461245260000,3.56,140],[1461245312000,2.1,140],[1461245346000,2.1,140],[1461245411000,3.5,140],[1461245442000,3.5,140],[1461245479000,-1,140],[1461245757000,-0.8,140],[1461245809000,-0.69,140]]

TIMEREQUESTED-hms.html

function buildTIMEREQUESTED() {
  var chart;
  var dataSource = 'getTrendData-TIMEREQUESTED-hms.php?format=json';
  var ChartHeight = window.innerHeight;

  function requestData() {
    $.ajax({
      url: dataSource,
      success: function(points) {
        chart.series[0].setData(points, true);
        setTimeout(requestData, 2500);
      },
      cache: false
    });
  }
  $(document).ready(function() {
    //add our div for the chart
    $("#container").append("<div id=chart-laptime style='width:100%''></div>");
    chart = new Highcharts.Chart({
      chart: {
        height: ChartHeight,
        renderTo: 'chart-laptime',
        defaultSeriesType: 'line',
        events: {
          load: function() {
            requestData();
          }
        },
      },
      tooltip: {
        enabled: true,
        formatter: function() {
          s = (this.y / 1000);
          m = Math.floor(s / 60);
          h = Math.floor(m / 60);
          s = s % 60;
          m = m % 60;
          h = h % 24;
          if (h < 9) h = "0" + h;
          if (m < 9) m = "0" + m;
          if (s < 9) s = "0" + s;
          return '<span style="color:black">Time Zero - </span>' + [m, s].join(':');
        }
      },
      title: {
        text: 'TIMEREQUESTED'
      },
      subtitle: {
        text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
      },
      xAxis: {
        type: 'datetime',
        title: {
          text: 'RACE TIME'
        }
      },
      yAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
          millisecond: '%H:%M:%S',
        },
        //dateFormat: {"%H:%M:%S.%L"}
        title: {
          text: 'TIMEREQUESTED'
        }
      },
      series: [{
        name: 'TIMEREQUESTED',
        showInLegend: false,
        //tooltip: {type: 'datetime',},
        data: [],
      }]
    }); //end chart               
  }); //end document.ready
}

通过这种方式,我可以正确显示单个系列,但是使用MySQL查询我可以从数据库中获取更多列,并在json文件的每一行中进行解析(如JSON文件中所示)从php请求,每个数组都有第三个值)但是我无法理解如何显示多个数据系列,在xAxis上始终是JSON文件的第一列,并且每次在yAxis上都有不同的列。

您能否就如何在同一图表上显示多个系列给我一些建议?非常感谢,

最好的问候。

2 个答案:

答案 0 :(得分:1)

var dataForTwoSeries = [[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0]]; //your data, just took 3 elements. Should work for any number of elements.
var seriesOne = [];
var seriesTwo = [];
$.each(dataForTwoSeries, function(index, dataPoints){
   var seriesOneDataPoint = [dataPoints[0], dataPoints[1]];
   var seriesTwoDataPoint = [dataPoints[0], dataPoints[2]];

   seriesOne.push(seriesOneDataPoint);
   seriesTwo.push(seriesTwoDataPoint);
});

然后你必须在图表对象中创建2个系列,如

series: [{
    name: 'seriesName1',
    showInLegend: false,
    data: [],
},{
    name: 'seriesName2',
    showInLegend: false,
    data: [],
}]

在requestData方法中,设置两者的数据,如

chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

编辑:更新后的代码,这些是您需要进行的更改。

$.ajax({url: dataSource, success: function(dataForTwoSeries) //dataForTwoSeries is the data you get from the request 
  {
  //var dataForTwoSeries = []; you don't need this.
  var seriesOne = []; //these two don't have to be global.
  var seriesTwo = [];
  $.each(dataForTwoSeries, function(index, dataPoints){

    var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
    var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];

    seriesOne.push(seriesOneDataPoint);
    seriesTwo.push(seriesTwoDataPoint);
  }); // draw chart after iteration and not during each interation
    chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
    chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it

    setTimeout(requestData, 2500);

  },
  cache: false
  });

答案 1 :(得分:0)

我已更新代码,现在没有语法错误,但我没有显示数据。我将把一些windows.allert()tu了解数据流被破坏的位置。

这是更新后的代码:

@Test
public void testForgotPassword()
{
    onView(withId(R.id.login_forgot_password)).perform(click());

    intended(allOf(
            hasAction(Intent.ACTION_VIEW),
            hasData(BuildConfig.FORGOT_PW_URL)));
}