PHP Fatal error: Cannot use object of type stdClass as array in錯誤

來源:互聯網
上載者:User

   下面一起來看看在php開發中碰到PHP Fatal error: Cannot use object of type stdClass as array in錯誤問題的解決辦法吧。

  普通的數組出現如下錯誤

 代碼如下  

<?php
Array (
 [0] => stdClass Object (
  [id] => 1
  [title] =>精彩推薦
  [size] => 280*150
  [pic] => ./uploadfiles/201402160422.jpg
  [state] => 0 )
 [1] => stdClass Object (
  [id] => 2
  [title] =>企業要聞
  [size] => 280*150
  [pic] => ./uploadfiles/201402160533.jpg
  [state] => 0 )
 )
?>

  後來百度搜尋一個關於差不多的問題,但對方是json資料

  php再調用json_decode從字串對象產生json對象時,如果使用[]操作符取資料,會得到下面的錯誤:

  Cannot use object of type stdClass as array

  產生原因:

 代碼如下  

$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 就可以了。

  好了現在回到我們原問題發現

  原來是不能直接用[]來顯示導致的,上面代碼的輸出是用的:$pic[0][title],改為$pic[0]->title後正常了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.