我有以下为我生成数据的功能:
function get_project_time() {
$name;
$desc;
$values;
$to;
$from;
$sql = $this->db->query("Select * from tbl_project")->result();
foreach ($sql as $value) {
$name = $value->project_name;
$desc = $value->project_status;
$start_date = $value->start_date;
$end_date = $value->end_date;
$unix_start_date = strtotime($start_date);
$unix_end_date = strtotime($end_date);
$to = "Date($unix_start_date)/";
$from = "Date($unix_end_date)/";
$e = new stdClass();
$f = new stdClass();
$e->name = $name;
$e->desc = $desc;
$f->to = $to;
$f->from = $from;
$e->values = array($f);
echo json_encode(array($e));
}
}
json输出以下列格式显示:
[{"name":"e-Campus and eLearning Project","desc":"in_progress","values":[{"to":"\/Date(1473627600)\/","from":"\/Date(1480626000)\/"}]}][{"name":"BloodLink Training Project","desc":"in_progress","values":[{"to":"\/Date(1474405200)\/","from":"\/Date(1475010000)\/"}]}][{"name":"Test Project","desc":"","values":[{"to":"\/Date(1474405200)\/","from":"\/Date(1475182800)\/"}]}]
我想清理数据,以便得到类似的内容:
[{"name":"e-Campus and eLearning Project","desc":"in_progress","values":[{"to":"/Date(1473627600)/","from":"/Date(1480626000)/"}]}][{"name":"BloodLink Training Project","desc":"in_progress","values":[{"to":"/Date(1474405200)/","from":"/Date(1475010000)/"}]}][{"name":"Test Project","desc":"","values":[{"to":"/Date(1474405200)/","from":"/Date(1475182800)/"}]}]
请告知我如何清理json数据?
答案 0 :(得分:0)
大部分代码都是冗余/无用的。你可以琐碎地拯救自己 有类似这样的行:
$sql = "SELECT project_name AS name, ... UNIX_TIMESTAMP(end_date) AS end_date etc...";
while($row = fetch()) {
$array[] = $row;
}
echo json_encode($array);
构建一个对象,只是为了将它类型化为一个数组,这完全是浪费和混乱。如果你想要一个数组,那么构建一个数组。做了“给我一个带有额外生菜的bigmac”,然后将它转换成鱼片。