PHP json_decode object時報錯Cannot use object of type stdClass as array


PHP json_decode object時報錯Cannot use object of type stdClass as array

php再調用json_decode從字符串對象生成json對象時,如果使用[]操作符取數據,會得到下面的錯誤
錯誤:
Cannot use object of type stdClass as array

產生原因:
$res = json_decode($res);
$res['key']; //把 json_decode() 后的對象當作數組使用。

解決方法(2種):
1、使用 json_decode($data, true)。就是使json_decode 的第二個變量設置為 true。
2、json_decode($res) 返回的是一個對象, 不可以使用 $res['key'] 進行訪問, 換成 $res->key 就可以了。

參考手冊:json_decode
Return Values:Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.


免責聲明!

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



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