Home > Backend Development > PHP Tutorial > php做为接口返回数据有关问题

php做为接口返回数据有关问题

WBOY
Release: 2016-06-13 12:09:29
Original
1602 people have browsed it

php做为接口返回数据问题
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":{}}这种形式呢?
------解决思路----------------------
一般没有必要,不然得重新写过了
------解决思路----------------------
返回时是这样的
echo json_encode($array);
你改成这样的
echo str_replace('[]', '{}', json_encode($array));

------解决思路----------------------
用JSON_FORCE_OBJECT参数即可

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



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




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

Related labels:
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