user5313398
user5313398

Reputation: 753

Extract data series from a JSON array for a Highcharts chart with 2 y-axis

I'm using Highcharts to create a line chart with 2 y-axis. Below is how I build my JSON array from a MySQL query:

$series1 = array();
$series1['name'] = 'V';
$series2 = array();
$series2['name'] = 'Speed';
while($row = $selectQueryResult1->fetch())
{
    $dateTimer1 = ($row['dateTimer']+$timeAdd)*1000;

    $series1['data'][] = array($dateTimer1,$row['v1']);
    $series2['data'][] = array($dateTimer1,$row['speed']);
}
$result = array();
array_push($result,$series1);
array_push($result,$series2);
echo json_encode($result, JSON_NUMERIC_CHECK);

Here is how I call the PHP script in jQuery:

$.post('getData.php', {b: begin,e: end}, function(data){

}

My issue now is how to extract the V data and Speed data into two variables because I need to pass them to the chart as two series of data, e.g. I have tried data[0], etc. Nothing seems to work.

///chart.series[0].setData( eval(vData) );
///chart.series[0].setData( eval(speedData) );

Upvotes: 1

Views: 965

Answers (1)

spenibus
spenibus

Reputation: 4409

You might want to add json as the 4th argument of your $.post to get the JSON parsed as an object, more info here: jQuery.post().

$.post('getData.php', {b: begin,e: end}, function(data){

}, 'json');

Reading your code tells us the structure of your data is as follows:

Array (
    [0] => Array
        (
            [name] => V
            [data] => Array
                (
                    [0] => Array
                        (
                            [0] => value of $dateTimer1
                            [1] => value of $row['v1']

Therefore the data series are:

  • data[0][data] for V.
  • data[1][data] for Speed.

Therefore:

chart.series[0].setData( data[0][data] );
chart.series[1].setData( data[1][data] );

When in doubt about a structure, simply print it out:

Upvotes: 1

Related Questions