今天調試一個php程序,發現出現了一個沒見過的錯誤,錯誤代碼:Cannot use object of type stdClass as array。這是怎么回事呢?查了半天縱欲發現這個竟然是json的寫法問題:
產生原因:
$res = json_decode($res);
$res['key']; //把 json_decode() 后的對象當作數組使用。
網上令狐蔥提供了兩種解決方法:
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.