1. 程式人生 > >PHP“Cannot use object of type stdClass as array”

PHP“Cannot use object of type stdClass as array”

php再呼叫json_decode從字串物件生成json物件時,如果使用[]操作符取資料,會得到下面的錯誤

錯誤:
Cannot use object of type stdClass as array

產生原因:
+展開 -PHP     $res = json_decode($res);

    $res['key']; //把 json_decode() 後的物件當作陣列使用。

解決方法(2種):
1、使用 json_decode($d, 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.