【问题标题】:How do I properly interact with the JSON return of twitter's API?如何正确与 twitter API 的 JSON 返回交互?
【发布时间】:2013-04-07 04:56:07
【问题描述】:

我正在使用 Twitter API(1.1 版)并试图通过 PHP 从 JSON 返回中获取特定变量。 $mentionsGET statuses/mentions_timeline 请求返回的 json_decode() 值。

我有以下 PHP:

foreach($mentions as $mention) {
    echo '<pre>' . print_r($mention) . "</pre><br>";
}

这按预期工作,但是当我将 ['created_at'] 添加到 $mention 时,我得到:

Fatal error: Cannot use object of type stdClass as array

根据twitter docs的预期回报:

[ // mentions
  { // mention
    "created_at": "Mon Sep 03 13:24:14 +0000 2012"
  }
]

这是 print_r($mention)(在循环内)返回的示例:

stdClass Object (
    [created_at] => Sat Apr 06 14:56:36 +0000 2013
)

这个 stdClass 是什么?如果可能的话,我该如何与之交互?

【问题讨论】:

    标签: php json twitter


    【解决方案1】:

    使用

    $mentions = json_decode($data, true)
    

    如果你查看docs,你会注意到assoc参数如果你想获取关联数组而不是对象。

    否则您可以使用$mention-&gt;created_at 访问对象属性

    【讨论】:

    • 非常感谢。虽然对结果感到困惑,但我尝试了$mention-&gt;'created_at',但显然忘记删除引号。两种方法都按预期工作。
    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 2015-09-22
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多