Kouja
Kouja

Reputation: 183

Need assistance for a part with json/php

I need help for generate the series data part into json

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container'
    },
    xAxis: {
        type: 'datetime'
    },
    series: [{
        data: [
            [Date.UTC(2010, 0, 1), 29.9],
            [Date.UTC(2010, 0, 2), 71.5],
            [Date.UTC(2010, 0, 3), 106.4],
            [Date.UTC(2010, 0, 6), 129.2],
            [Date.UTC(2010, 0, 7), 144.0],
            [Date.UTC(2010, 0, 8), 176.0]
         ]
    }]
});

My php part

foreach ($behaviour as $value) {
    $chart['xAxis']['categories'][]= time($value['date']);
}

Json output

[1318354710,1318354710,1318354710,1318354710]

I don't know what I need to do with my php code to do this part with a valid json.

part where I need help

series: [{
    data: [
        [Date.UTC(2010, 0, 1), 29.9],
        [Date.UTC(2010, 0, 2), 71.5],
        [Date.UTC(2010, 0, 3), 106.4],
        [Date.UTC(2010, 0, 6), 129.2],
        [Date.UTC(2010, 0, 7), 144.0],
        [Date.UTC(2010, 0, 8), 176.0]
     ]
}]

How can I solve this?

Upvotes: 0

Views: 340

Answers (1)

Herbert
Herbert

Reputation: 5778

Date.UTC returns the number of milliseconds in a date string since midnight of January 1, 1970. This is the same as a UNIX timestamp. So [Date.UTC(2010, 0, 1), 29.9] translates to [1262304000, 29.9].

There are a number of ways to get this timestamp in PHP. One simple (and object oriented) way is to use the DateTime class:

$time = new DateTime($value['date'], new DateTimezone('UTC'));
$chart['xAxis']['categories'][] = $time->getTimestamp();

Update

Without knowing the ins and outs of your code, the best I can do is offer some sample code:

<?php
// sample data
$behaviour = array(
    array(
        'date' => '2010-01-01',
        'datum' => 29.9
    ),
    array(
        'date' => '2010-01-02',
        'datum' => 71.5
    ),
    array(
        'date' => '2010-01-03',
        'datum' => 106.4
    ),
    array(
        'date' => '2010-01-06',
        'datum' => 129.2
    ),
    array(
        'date' => '2010-01-07',
        'datum' => 144
    ),
    array(
        'date' => '2010-01-08',
        'datum' => 176
    )
);

// creates the container information
$output = array(
    'chart' => array(
        'renderTo' => 'container'
    ),

    'xAxis' => array(
        'type' => 'datetime'
    ),

    'series' => array()
);

// adds the sample data
foreach ($behaviour as $value) {
    $time = new DateTime($value['date'], new DateTimezone('UTC'));
    $output['series'][0]['data'][] = array(
        $time->getTimestamp(), $value['datum']
    );
}

// output as JSON
header('Content-type: application/json');
echo json_encode($output); 
?>

Feel free to adapt it to your actual code.

Upvotes: 1

Related Questions