PHP:datetime字符串到Google图表的json日期时间
几天来,我一直在努力将datetime字符串转换为json datetime以包含在Google图表中,现在我正在寻求帮助 我拥有的日期格式是“2008-01-15 14:30:45”,我认为需要将其转换为日期(2008,0,15,14,30,45),然后再插入数组,然后转换为谷歌图表的JSON格式 我们的目标主要是能够将趋势线添加到图表中,但如果时间刻度也正确,那就太好了:) 代码如下 非常感谢您的帮助 斯蒂夫PHP:datetime字符串到Google图表的json日期时间,php,json,datetime,Php,Json,Datetime,几天来,我一直在努力将datetime字符串转换为json datetime以包含在Google图表中,现在我正在寻求帮助 我拥有的日期格式是“2008-01-15 14:30:45”,我认为需要将其转换为日期(2008,0,15,14,30,45),然后再插入数组,然后转换为谷歌图表的JSON格式 我们的目标主要是能够将趋势线添加到图表中,但如果时间刻度也正确,那就太好了:) 代码如下 非常感谢您的帮助 斯蒂夫 <?php require_once 'dbconfig
<?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>
var currheight=document.documentElement.clientHeight;
window.onresize=函数(){
if(currheight!=document.documentElement.clientHeight){
location.replace(location.href);
}
}
//加载可视化API和piechart包。
load('visualization','1',{'packages':['corechart']});
//将回调设置为在加载Google Visualization API时运行。
setOnLoadCallback(下载图表);
函数下载图表(){
//使用从服务器加载的JSON数据创建我们的数据表。
var ddata=new google.visualization.DataTable();
变量选项={
//标题:“速度测试数据”,
//标题位置:“无”,
is3D:'正确',
宽度:“100%”,
身高:500,
哈克斯:{标题:'时间',
方向:1,,
是的,
倾斜角度:90,
textStyle:{fontSize:8}//或所需的数字
},
变量:{title:'Speed Mbit/s'},
图例:{位置:'bottom'},
图表区:{顶部:45,高度:40%,
背景颜色:{
笔划:“#ccc”,
冲程宽度:1},
}
//趋势线:{0:{color:'green',}}//为数据系列0绘制一条趋势线。
};
//实例化并绘制图表,传入一些选项。
//别忘了检查你的部门ID
var chart=new google.visualization.LineChart(document.getElementById('download_chart_div');
图表绘制(ddata,选项);
}
下载速度
试试这个
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']));
下面是将从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);
}
函数JSdate($in$type){
如果($type=='date'){
//日期图案为“yyyy MM dd”
preg_match('/(\d{4})-(\d{2})-(\d{2})/',$in,$match);
}elseif($type=='datetime'){
//日期时间模式为“yyyy-MM-dd hh:MM:ss”
预匹配('/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})/',$in,$match);
}
$year=(int)$match[1];
$month=(int)$match[2]-1;//索引之间的月转换
$day=(int)$match[3];
如果($type=='date'){
返回“日期($year,$month,$day)”;
}elseif($type=='datetime'){
$hours=(int)$match[4];
$minutes=(int)$match[5];
$seconds=(int)$match[6];
返回“日期($year、$month、$day、$hours、$minutes、$seconds)”;
}
}
$presult=$conn->query('SELECT starttime,server_ping FROM speeddata');
$prows=array();
$ptable=array();
$ptable['cols']=数组(
//对于图表,这些标签表示列标题。
数组('label'=>'StartTime','type'=>'datetime'),
数组('label'=>'Ping','type'=>'number'),
//数组('label'=>'Ping','type'=>'number')
);
/*从$result中提取信息*/
foreach($p){
$date=JSdate($p['starttime',datetime);
//echo JSdate($p['starttime','datetime');
$ptemp=array();
//下一行将用于对图表进行切片+
$new_value=array();
对于($i=0;$i$date);
$prows[]=数组('c'=>$ptemp);
}
我试图找到一个解决您的问题的不那么复杂的解决方案。由于Symfony中的JSONResponse,我用PHP发送了一个JSON响应。我在PHP中做的一个小技巧是将dateTime转换为'Y,m,d'格式
$tableTimeline = [];
foreach ($resources as $resource)
{
if($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[0] != null)
array_push($tableTimeline, [
$resource->getTechnician()->getUsername(),
$resource->getBusiness()->getName()." (".$this->get('platform.gantt')->baseTime($resource->getBusiness())." h/s)",
// format -> new Date(1809, 3, 26)
date_format($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[0], 'Y, m, d'),
date_format($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[1], 'Y, m, d'),
]);
}
return new JsonResponse($tableTimeline);
然后,由于Ajax调用,我检索了JS中的数据,并将JSON对象修改为数组
success: function (chart_values) {
let arrayData = $.map(chart_values, function (value, index) {
return [value];
});
arrayData = changeToDate(arrayData);
draw_chart(arrayData); // call your drawing function!
}
这段代码的小技巧在于changeToDate函数->我将2&3列的值从字符串日期('Y,m,d')更改为可读的JS日期
function changeToDate(arrayData) {
arrayData.forEach(data => {
let startDate = new Date(data[2]);
let endDate = new Date(data[3]);
data[2] = startDate;
data[3] = endDate;
});
return arrayData;
}
然后我绘制了图表,这要归功于draw_chart函数,它完美地转换了字符串,我想,但在我的代码中我把它放在了哪里?我尝试了$dtemp[]=array('v'=>$d[date('Y,m,d,G,I,s',strottime('starttime'))];但是什么也没有得到:(出于某种原因返回空值。Stevew只需尝试一下$dtemp[]=array('v'=>date('Y,m,d,G,i,s',strotime($d['starttime'));出于某种给我一个空白屏幕的原因,我也尝试过用引号将其括起来,但没有效果。我认为您必须将其放入一个类似$date=date('Y,m,d,G,i,s',strotime($d)的数组中['starttime']];$spolded_date=explode(',',$date);$new_value=array();for($i=0;$i