清理 Json URL 数据 [重复]
Posted
技术标签:
【中文标题】清理 Json URL 数据 [重复]【英文标题】:Clean up Json URL data [duplicate] 【发布时间】:2017-02-04 07:09:20 【问题描述】:我有以下为我生成数据的函数:
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 数据?
【问题讨论】:
***.com/questions/10210338/… 你做错了。您正在循环中执行echo json_encode(..)
,因此您正在生成多个独立的 json 字符串。您需要在循环内构建一个数组/对象。您只需在构建完成时在流程结束时进行编码。
【参考方案1】:
大部分代码都是多余的/无用的。你可以为自己节省很多 类似这样的行数:
$sql = "SELECT project_name AS name, ... UNIX_TIMESTAMP(end_date) AS end_date etc...";
while($row = fetch())
$array[] = $row;
echo json_encode($array);
构建一个对象,只是为了将它类型转换为一个数组,这完全是浪费和混乱。如果你想要一个数组,然后构建一个数组。完成“给我一个带有额外生菜的巨无霸”,然后将其转换为菲力鱼。
【讨论】:
以上是关于清理 Json URL 数据 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
file_get_contents() 从 url 而不是 json 返回原始数据 [重复]
遍历一个url数组并将它们传递给get_json,返回新的数据数组[重复]