我使用PHP对MySQL中的JSON进行了RESTfully编码,其中一列是日期,在MySQL中是这样的01/03/15 06:00,在JSON编码中是这样。
[["01/03/15 06:00","89"],["02/03/15 06:00","87"]]
我如何将其转换为以下代码,其中以毫秒为单位的日期时间戳
[["1420245000000","89"],["1422923400000","87"]]
JSON编码的PHP代码
private function productionhourlys(){
if($this->get_request_method() != "GET"){
$this->response('',406);
}
$query="SELECT distinct c.Date, c.RoA FROM productionhourlys c order by c.productionhourlyNumber desc";
$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
if($r->num_rows > 0){
$result[] = array_values([]);
while($row = $r->fetch_row()) {
$result[] = $row;
}
$this->response($this->json($result), 200); // send user details
}
$this->response('',204); // If no records "No Content" status
}
如果您想在服务器端进行转换,那么在将当前$row分配给$result:之前,请在while循环中进行转换
EDIT:当OP请求时,将时间戳(以秒为单位)转换为毫秒
while($row = $r->fetch_row()) {
$row[0] = strtotime($row[0]); // convert to unix timestamp (in seconds)
$row[0] = 1000 * $row[0]; // convert seconds to milliseconds
$result[] = $row;
}
我也不确定这条线的目的是什么:
$result[] = array_values([]);
如果你只是创建一个新的空数组,你可以这样做:
$result = array();
试试这个例子:
<?php
$json = '[["01/03/15 06:00","89"],["02/03/15 06:00","87"]]';
$array = json_decode($json, true);
$array = array_map(function($n) {$date = new DateTime($n[0]); return array($date->format('U'), $n[1]);}, $array);
$json = json_encode($array);
echo $json;
输出:
[["1420282800","89"],["1422961200","87"]]