[轉]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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM