0xDECAFBAD
0xDECAFBAD

Reputation: 117

How would I convert this array to usable javascript array?

I have php code that returns this from a database,

[
{
    "Time": "2012-11-27 16:10:35",
    "NumPlayers": "1"
},
{
    "Time": "2012-11-27 16:24:55",
    "NumPlayers": "1"
},
{
    "Time": "2012-11-27 16:25:37",
    "NumPlayers": "2"
},
{
    "Time": "2012-11-27 16:29:33",
    "NumPlayers": "2"

The times are MySQL timestamps. I need to get it into this format to use with Highcharts javascript charting.

data: [
[Date.UTC(1970,  9,  9), 0   ],
[Date.UTC(1970,  9, 14), 0.15],
[Date.UTC(1970, 10, 28), 0.35],
[Date.UTC(1970, 11, 12), 0.46],

I'm having trouble figuring out how to loop through the MySQL results and convert the timestamps to javascript Date.UTC objects. I need to place the NumPlayers value after the Date.UTC objects, and output it in the format below. I'm a PHP and javascript noob :\

It should look something like this:

data: [
[Date.UTC(2012, 11, 27, 16, 10, 35), 1],
[Date.UTC(2012, 11, 27, 16, 24, 55), 1],
[Date.UTC(2012, 11, 27, 16, 25, 37), 2],
[Date.UTC(2012, 11, 27, 16, 29, 33), 2],

Upvotes: 1

Views: 426

Answers (5)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

The best way to provide data to Highcharts is getting data formated from database, so that you don't have to do it on client side.

To do it you just have to change your query to something like the following.

Backend
$query = "SELECT UNIX_TIMESTAMP(date) * 1000 AS 'date', value FROM ...";

Then to send the result to frontend:
echo json_encode($result);

Frontend
To get the result on frontend, this case using jQuery and assuming that url is your url:

$.getJSON(url, function(json) {
    // decode json
    var data = $.parseJSON(json);
    // Then you just have to pass it to your series
});

Or better, store date values in UTC.

Upvotes: 1

Sean Vieira
Sean Vieira

Reputation: 159865

You can split the time string into sections using /[^\d]+/g:

var finalData = [], numbers=/[^\d]+/g, item, dateParts, newDate;
for (var i=0, l=data.length; i<l; i++) {
     item = data[i];
     dateParts = item.Time.split(numbers);
     newDate = Date.UTC.apply(Date, dateParts);
     finalData.push([newDate, item.NumPlayers]);
}

See also: MDN's documentation on JavaScript regular expressions (/[^\d]/g is a regex).

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92274

You should realize that Date.UTC(2012, 11, 27, 16, 10, 35) simply returns the number of milliseconds since the epoch (1356624635000). Therefore, you can just convert your object into UNIX timestamps (times a 1000 since JS works with millisecond timestamps, but PHP works with seconds).

Sample Code

$data = '[{"Time": "2012-11-27 16:10:35", "NumPlayers": "1"}, {"Time": "2012-11-27 16:24:55", "NumPlayers": "1"}]';

// Make sure date is parsed as UTC
date_default_timezone_set("UTC");

// Convert items into the desired format
$mapper = function($item) {
    return array(strtotime($item->Time)*1000, $item->NumPlayers);
}

echo json_encode(array_map($mapper, json_decode($data)));

Output

[[1354032635000,"1"],[1354033495000,"1"]]

Upvotes: 2

Havelock
Havelock

Reputation: 6968

You seem to be getting straight JSON from your database, which you can always convert into an array:

$data = '[{"Time": "2012-11-27 16:10:35", "NumPlayers": "1"}, {"Time": "2012-11-27 16:24:55", "NumPlayers": "1"}]';
$arrayData = json_decode($data, true);

After which you can simply iterate through the array and print out the contents of the array in the JS format you need. Something like that:

echo 'data: [' . PHP_EOL;
foreach ($arrayData as $item) {
    echo '[Date.UTC(';
    $tmp = preg_split( '/(-| |\:)/', $item['Time'] );
    echo implode(', ', $tmp);
    echo '), ' . $item['NumPlayers'] . '],';
    echo PHP_EOL;
}
echo PHP_EOL . '];';

Upvotes: 1

kossoy
kossoy

Reputation: 11

    var php_data = [
        {
            "Time": "2012-11-27 16:10:35",
            "NumPlayers": "1"
        },
        {
            "Time": "2012-11-27 16:24:55",
            "NumPlayers": "1"
        }
    ];

    var length = php_data.length;
    hc_data = [];

    for(var i = 0; i< length; i++){
      php_date = new Date(php_data[i]["Time"]);
      hc_data.push(
        [
            Date.UTC(
                php_date.getFullYear(), 
                php_date.getMonth() + 1, 
                php_date.getDate()
            ),
            php_data[i]["NumPlayers"]
        ]
      );
    }

    // hc_data is your Array

Upvotes: 0

Related Questions