进程SQL返回JSON

时间:2016-12-20 21:49:19

标签: php json

我正在玩这里构建我的第一个JSON API。我有以下函数从我的SQL查询中返回JSON:

>>> ranges = [range(i) for i in range(5)]
>>> [*item for item in ranges]
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]

>>> {*item for item in ranges}
{0, 1, 2, 3}

注意我已经注释了开始和结束function processResponse($response) { // if (!$key) echo '['; for ($i=0;$i<count($response);$i++) { echo ($i>0?',':'').json_encode($response); } // if (!$key) echo ']'; } 括号,因为我注意到多个(不必要的)嵌套数组。这允许这样的事情:[ ]否则它将是一个嵌套数组,我需要做类似$json[0]->email;

的事情

但是,当我对处理后的输出执行$json[0][0]->email;时,我得到一个null。添加json_decode()后退会解决此问题。

所以我想我的问题是为什么[]会为此返回json_decode()

null

为什么这样做:

[{"inventory_id":7,"start":null,"expiration":null,"created":"2016-12-05 10:58:23","updated":"2016-12-08 15:29:56","item_name":"Tour Ticket (Per Person)","default_rate":null,"quantity":5,"bookings_count":"6","itinerary_count":"8","group_name":"Winery","location_name":"Location 1","status":"Active","type_name":"Tour","username":"email@address.com","user_id":4},{"inventory_id":20,"start":null,"expiration":null,"created":"2016-12-06 12:33:18","updated":"2016-12-08 15:41:12","item_name":"Tasting Ticket","default_rate":null,"quantity":10,"bookings_count":"0","itinerary_count":"0","group_name":"Winery","location_name":"Location 1","status":"Archived","type_name":"Ticket","username":"email@address.com","user_id":4}]

有没有更好的方法来构建JSON输出?

1 个答案:

答案 0 :(得分:0)

您只需要将数据作为关联数组从db返回,然后调用json_encode,您将很乐意去。它为您完成所有工作。

$data = ["name" => "john doe", "age" : 33];
print json_enconde($data); // {"name" : "john doe", "age": 33 }

$data = [
    ["name" => "john doe", "age" : 33],
    ["name" => "mary doe", "age" : 28]
];
print json_enconde($data); // [{"name" : "john doe", "age": 33 }, {"name" : "mary doe", "age": 28 }]

正如你所看到的...... $ data只需要是一个关联数组,所以从db中获取它

请注意,有时您的数据不适合UTF8解析为json。当您从数据库中重新调整blob时,这一点尤其正确。

我真的建议你阅读这个

http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP/