Cannot use object of type stdClass as array錯誤的解決方法

2011-12-19 10:34:38來源:donews作者:

今天調(diào)試一個php程序,發(fā)現(xiàn)出現(xiàn)了一個沒見過的錯誤,錯誤代碼:Cannot use object of type stdClass as array。這是怎么回事呢?查了半天縱欲發(fā)現(xiàn)這個竟然是json的寫法問題:

今天調(diào)試一個php程序,發(fā)現(xiàn)出現(xiàn)了一個沒見過的錯誤,錯誤代碼:Cannot use object of type stdClass as array。這是怎么回事呢?查了半天縱欲發(fā)現(xiàn)這個竟然是json的寫法問題:

產(chǎn)生原因:

$res = json_decode($res);

$res['key']; //把 json_decode() 后的對象當(dāng)作數(shù)組使用。

網(wǎng)上令狐蔥提供了兩種解決方法:

1、使用 json_decode($d, true)。就是使json_decode 的第二個變量設(shè)置為 true。

2、json_decode($res) 返回的是一個對象, 不可以使用 $res['key'] 進(jìn)行訪問, 換成 $res->key  就可以了。

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

關(guān)鍵詞:php