[英]Parsing MySQL to JSON array, with data manipulation in PHP
I'm tring to parse a MySQL request to a JSON file, with this PHP function, 我正在尝试使用此PHP函数将MySQL请求解析为JSON文件,
<?php
//Define possible Argument request
$format = $_GET['format'];
if($format=='json') {
header("Content-type: text/json");
}
//Define database credential
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
try {
//Open connection to mysql_db from defined Database credentials
$connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
//Fetch table rows from mysql db
$sql = "SELECT TS, time1, time2, time3 FROM time ORDER BY TS";
$result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
//Create an array
$series0 = array();
$series0['name'] = 'TS';
$series1 = array();
$series1['name'] = 'time1';
$series2 = array();
$series2['name'] = 'time2';
$series3 = array();
$series3['name'] = 'time3';
while($r = mysqli_fetch_array($result))
{
$series0['data'][] = $r['TS'];
$series1['data'][] = $r['time1'];
$series2['data'][] = $r['time2'];
$series3['data'][] = $r['timez3'];
}
$result = array();
array_push($result,$series0);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($connection);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Who gives me this JSON output: 谁给我这个JSON输出:
[{
"name": "TS",
"data": ["00:08:31.227","00:09:02.434","00:09:38.573"]
},{
"name":"time1",
"data":["00:05:11.220","00:05:05.420","00:03:32.540"]
},{
"name":"time2",
"data":["00:04:11.820","00:08:05.660","00:01:24.330"]
},{
"name":"time3",
"data":["00:02:11.990","00:09:05.570","00:15:25.200"]
}]
Now the problem is that I have to convert the times from "HH:MM:SS.fff", to seconds (SS.fff), but trying to apply my conversion function I came to an error becouse I cant applay my formulas to an array, is there a way to intercept the data and manipulate it before they goes inside the array? 现在的问题是我必须将时间从“ HH:MM:SS.fff”转换为秒(SS.fff),但是尝试应用转换函数时出现错误,因为我无法将公式应用于数组,有没有一种方法可以在数据进入数组之前拦截数据并对其进行处理?
And a second minor problem, becouse the final array will get 100+ dataseries, is there a way to don't assign manually the name to the series, but give them the same name as the column of MySQL table from where they came from?? 还有第二个小问题,因为最终数组将获得100个以上的数据序列,有没有办法不手动为该序列分配名称,而是给它们命名与它们来自的MySQL表列相同的名称? ?
Thank for all the suggestions, Best regards. 感谢所有建议,最诚挚的问候。
You can use mysql TIME_TO_SEC function. 您可以使用mysql TIME_TO_SEC函数。
mysql> SELECT TIME_TO_SEC('22:23:00');
-> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
-> 2378
so change 所以改变
$sql = "SELECT TS, time1, time2, time3 FROM time ORDER BY TS";
to 至
$sql = "SELECT TS, TIME_TO_SEC(time1), TIME_TO_SEC(time2), TIME_TO_SEC(time3) FROM time ORDER BY TS";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.