我使用PHP从MySQL编译了JSON,一列是日期,在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
}
答案 0 :(得分:1)
如果你想在服务器端进行转换,那么在将当前$ row分配给$ result之前,在while循环中进行转换:
编辑: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();
答案 1 :(得分:0)
试试这个例子:
<?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"]]