php做为接口返回数据问题

WBOY
Release: 2016-06-23 13:45:59
Original
2222 people have browsed it

php做为接口返回数据问题
有数据的时候返回的是{"status":"0","message":"\u9a8c\u8bc1\u7801\u9519\u8bef","data":{"a":"1"}},其中data里的是数组$result,如果$result为空的话,$result = array();   输出{"status":"0","message":"\u9a8c\u8bc1\u7801\u9519\u8bef","data":[]},返回的data就是中括号了,如何把data换成大括号,{"status":"0","message":"\u9a8c\u8bc1\u7801\u9519\u8bef","data":{}}这种形式呢?


回复讨论(解决方案)

一般没有必要,不然得重新写过了

一般没有必要,不然得重新写过了


没办法,前端IOS和安卓催的紧,非得要求这种格式

返回时是这样的
echo json_encode($array);
你改成这样的
echo str_replace('[]', '{}', json_encode($array));

用JSON_FORCE_OBJECT参数即可

<?php$a=array();var_dump(json_encode($a,JSON_FORCE_OBJECT));$a=array(1,2,3);var_dump(json_encode($a,JSON_FORCE_OBJECT));$a=array("ret"=>0);var_dump(json_encode($a,JSON_FORCE_OBJECT));
Copy after login



string(2) "{}"string(19) "{"0":1,"1":2,"2":3}"string(9) "{"ret":0}"
Copy after login



JSON_FORCE_OBJECT (integer)  
使一个非关联数组输出一个类(Object)而非数组。 在数组为空而接受者需要一个类(Object)的时候尤其有用。 自 PHP 5.3.0 起生效。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!