PHP: дата и время в формате JSON DateTime для Google Chart

В течение нескольких дней я пытался преобразовать строку datetime в json datetime для включения в Google Chart, и теперь мне нужна помощь.

У меня есть формат даты «2008-01-15 14:30:45», который, я считаю, необходимо преобразовать в дату (2008, 0, 15, 14, 30, 45) перед вставкой в ​​массив, а затем преобразовывается в формат JSON для диаграммы Google.

Цель состоит, прежде всего, в том, чтобы иметь возможность добавить линию тренда на график, но было бы неплохо иметь правильную шкалу времени :).

Кодекс следует.

Любая помощь с благодарностью.

SteveW

    <?php

require_once 'dbconfig.php';
/* Your Database Name */
$dbname = 'speedtest';

try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//DOWNLOAD CHART
$dresult = $conn->query('SELECT starttime, download FROM speeddata');

$drows = array();
$dtable = array();
$dtable['cols'] = array(

// Labels for your chart, these represent the column titles.
array('label' => 'StartTime', 'type' => 'string'), //change 'string' to datetime
array('label' => 'Download Speed', 'type' => 'number'),

);
/* Extract the information from $result */
foreach($dresult as $d) {

$dtemp = array();

// the following line will be used to slice the chart
$dtemp[] = array('v' =>  $d['starttime']); //starttime to Date(2008, 0, 15, 14, 30, 45) format?
// Values of each slice
$dtemp[] = array('v' => (DOUBLE) $d['download']);
// $temp[] = array('v' => (DOUBLE) $r['server_name']);

$drows[] = array('c' => $dtemp);
}

$dtable['rows'] = $drows;

// convert data into JSON format
$djsonTable = json_encode($dtable);
//echo $djsonTable;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

?>

<html lang="en">
<head>
<meta charset="UTF-8">

<!--Reload page on resize-->
<script type="text/javascript">
var currheight = document.documentElement.clientHeight;
window.onresize = function(){
if(currheight != document.documentElement.clientHeight) {
location.replace(location.href);
}
}
</script>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(downloadChart);function downloadChart() {

// Create our data table out of JSON data loaded from server.
var ddata = new google.visualization.DataTable(<?=$djsonTable?>);
var options = {
//title: 'Speedtest Data',
//titleposition: 'none',
is3D: 'true',
width: '100%',
height: 500,
hAxis:{title: 'Time',
direction:1,
slantedText:true,
slantedTextAngle:90,
textStyle : { fontSize: 8} // or the number you want
},
vAxis:{title: 'Speed Mbit/s'},
legend: { position: 'bottom' },
chartArea: { top: 45, height: '40%',
backgroundColor: {
stroke: '#ccc',
strokeWidth: 1},

}
//trendlines: { 0: {color: 'green',} }    // Draw a trendline for data series 0.};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID

var chart = new google.visualization.LineChart(document.getElementById('download_chart_div'));
chart.draw(ddata, options);

}

</script>

</head>

<body class="site">

<main class="site-content">
<!--this is the div that will hold the chart-->

<div id="chart_title">Download Speed</div>
<div id="download_chart_div"></div>
<hr><br></main>

</body>
</html>

0

Решение

Просто попробуйте это

echo date('Y, m, d, G, i, s', strtotime('2008-01-15 14:30:45'));

В вашем коде будет выглядеть так

$dtemp[] = array('v' => date('Y, m, d, G, i, s', strtotime($d['starttime']));
0

Другие решения

Следующее в конечном итоге сделало то, что требовалось для вставки даты и времени, извлеченных из базы данных mysql, в диаграмму Google Я уверен, что есть более элегантный способ, но он работает! 🙂

Функция идет в начале PHP

    function JSdate($in,$type){
if($type=='date'){
//Dates are patterned 'yyyy-MM-dd'
preg_match('/(\d{4})-(\d{2})-(\d{2})/', $in, $match);
} elseif($type=='datetime'){
//Datetimes are patterned 'yyyy-MM-dd hh:mm:ss'
preg_match('/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})/', $in, $match);
}

$year = (int) $match[1];
$month = (int) $match[2] - 1; // Month conversion between indexes
$day = (int) $match[3];

if ($type=='date'){
return "Date($year, $month, $day)";
} elseif ($type=='datetime'){
$hours = (int) $match[4];
$minutes = (int) $match[5];
$seconds = (int) $match[6];
return "Date($year, $month, $day, $hours, $minutes, $seconds)";
}
}$presult = $conn->query('SELECT starttime, server_ping FROM speeddata');$prows = array();
$ptable = array();
$ptable['cols'] = array(

// Labels for your chart, these represent the column titles.
array('label' => 'StartTime', 'type' => 'datetime'),
array('label' => 'Ping', 'type' => 'number'),
//array('label' => 'Ping', 'type' => 'number')
);
/* Extract the information from $result */
foreach($presult as $p) {

$date = JSdate($p['starttime'],datetime);
//echo JSdate($p['starttime'],'datetime');
$ptemp = array();

// the following line will be used to slice the chart+

$new_value = array();
for ($i=0; $i < count($new_value);
$i++): array_push($new_value, $date[$i]);
endfor;

$ptemp[] = array('v' => $date);

$prows[] = array('c' => $ptemp);
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector