[转]php 中 json_decode 解析返回结果为 null 解决办法

json_decode结果为null的解决方法
传参数时,有时需要传数组,但是数组不方便传输,所以通常会转化为json串传输。接收到参数需要用json_decode处理。

json_decode的语法
mixed json_decode ( string json[,booljson[,boolassoc = false [, int depth=512[,intdepth=512[,intoptions = 0 ]]] )

需要注意
此函数仅适用于UTF-8编码的字符串
assoc默认为false时,返回objects,如果需要返回数组格式,需要设置为true
举个例子:

$json = '{"a":1,"b":2}';

var_dump(json_decode($json));

var_dump(json_decode($json, true));

1
2
3
4
结果为:

object(stdClass)#1 (2){

["a"] => int(1)

["b"] => int(2)

}

array(2){

["a"] => int(1)

["b"] => int(2)

}

1
2
3
4
5
6
7
8
9
问题:
运行过程中,可以正常返回数组,但是有出现结果为null的情况。

排查过程:
打印出接收的参数,发现是完整的json串

在json解析网站上可以返回正常的数组值

解决方案:
原因:参数在传递过程进行了编码转译导致的。

info=stripslashes(htmlentitydecode(info=stripslashes(htmlentitydecode(json));

info=jsondecode(info=jsondecode(info,true);

html_entity_decode()函数:把HTML实体转换成一些预定义的字符。html_entity_decode() 函数是 htmlentities() 函数的反函数。

stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。该函数可用于清理从数据库中或者从 HTML 表单中取回的数据。

经过这样的处理,可以得到正常的数组数据
---------------------
作者:快乐者开心
来源:CSDN
原文:https://blog.csdn.net/guaiguainu87/article/details/74551563
版权声明:本文为博主原创文章,转载请附上博文链接!

QQ:309488423 Email:leiliu_lucfer@163.com
原文地址:https://www.cnblogs.com/leiliu-lucifer/p/10334904.html