【问题标题】:Cannot use object of type stdClass as array不能将 stdClass 类型的对象用作数组
【发布时间】:2012-03-29 11:58:09
【问题描述】:

所有, 我正在使用这样的功能:

function themeblvd_twitter_slider_default( $tweet, $options, $username ) {
    echo $tweet[0]->text;
}

函数中的行给了我以下错误: 致命错误:不能将 stdClass 类型的对象用作数组

当我在 $tweet 上执行 print_r 时,我得到以下输出:

对象(stdClass)#70(19){ ["in_reply_to_screen_name"]=> 空值 [“in_reply_to_user_id”]=> 空值 [“in_reply_to_status_id”]=> 空值 [“坐标”]=> 空值 [“转推”]=> 布尔(假) [“created_at”]=> 字符串(30)“2012 年 3 月 12 日星期一 16:54:05 +0000” [“id_str”]=> 字符串(18)“12345553333” [“截断”]=> 布尔(假) [“用户”]=> 对象(stdClass)#78 (38) { [“身份证”]=> 整数(522392463) ["profile_image_url_https"]=> 字符串(73)“https://si0.twimg.com/profile_images/1891637329/turntable_dots_normal.jpg” ["contributors_enabled"]=> 布尔(假) ["profile_use_background_image"]=> 布尔(真) [“语言”]=> 字符串(2)“en” [“id_str”]=> 字符串(9)“522392463” ["default_profile_image"]=> 布尔(假) ["geo_enabled"]=> 布尔(假) ["profile_text_color"]=> 字符串(6)“333333” ["is_translator"]=> 布尔(假) [“收藏夹数”]=> 整数(0) [“位置”]=> string(11) "伊利诺伊州芝加哥" [“时区”]=> 空值 ["utc_offset"]=> 空值 ["show_all_inline_media"]=> 布尔(假) ["profile_sidebar_border_color"]=> 字符串(6)“C0DEED” [“名称”]=> 字符串(20)“名称” [“受保护”]=> 布尔(假) ["profile_background_image_url_https"]=> 字符串(49)“https://si0.twimg.com/images/themes/theme1/bg.png” ["profile_background_tile"]=> 布尔(假) [“以下”]=> 空值 ["profile_sidebar_fill_color"]=> 字符串(6)“DDEEF6” [“follow_request_sent”]=> 空值 ["default_profile"]=> 布尔(真) ["statuses_count"]=> 整数(2) [“描述”]=> string(56) "描述" [“通知”]=> 空值 [“已验证”]=> 布尔(假) ["profile_background_color"]=> 字符串(6)“C0DEED” ["listed_count"]=> 整数(0) ["profile_image_url"]=> 字符串(71)“http://a0.twimg.com/profile_images/1891637329/turntable_dots_normal.jpg” ["profile_background_image_url"]=> 字符串(47)“http://a0.twimg.com/images/themes/theme1/bg.png” ["followers_count"]=> 整数(3) [“网址”]=> 字符串(28)“http://www.website.com” ["friends_count"]=> 整数(9) [“created_at”]=> 字符串(30)“2012 年 3 月 12 日星期一 16:38:11 +0000” ["profile_link_color"]=> 字符串(6)“0084B4” [“屏幕名称”]=> string(10) "用户名" } [“in_reply_to_status_id_str”]=> 空值 [“地理”]=> 空值 [“转推数”]=> 整数(0) [“收藏”]=> 布尔(假) [“地点”]=> 空值 [“来源”]=> 字符串(3)“网络” [“in_reply_to_user_id_str”]=> 空值 [“贡献者”]=> 空值 [“身份证”]=> 浮动(1.7924891374269E+17) [“文本”]=> string(140) "这是推文" }

如何在不出错的情况下访问文本?

谢谢!

【问题讨论】:

  • 您正在调用不存在的$tweet[0]...

标签: php arrays


【解决方案1】:

错误的含义正是它,$tweet 不是一个数组,因此尝试获取它的第 0 个索引是没有意义的。

$tweet->text 应该没问题:)

如果您确定 $tweet 是一组推文信息:

foreach($tweet as $t) {
   echo $t->text;
}

【讨论】:

  • 如果我有不止一条推文,那会是什么样子?
【解决方案2】:

最简单的方法是将$tweet 转换为数组:

$tweet = (array)$tweet;

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多