"不能使用stdClass类型的对象作为数组"使用Twitter API搜索推文时出错

时间:2017-12-21 20:11:32

标签: laravel twitter oauth

我目前正在开展一个项目,我正在尝试搜索推文,然后将其保存在数据库中。对于这个项目,我使用的是Laravel和TwitterOAuth

这里是代码:

class TwitterController extends BaseController
{
public function test() {
    $connection = new TwitterOAuth('',
        '',
        '',
        '');
    $content = $connection->get('account/verify_credentials');

    $tweets = $connection->get('search/tweets',
        ['q' => "cryptocurrency"]);

    foreach($tweets as $tweet) {



        $tweet_id = $tweet[0]->id;
        $oembed_j = file_get_contents('https://publish.twitter.com/oembed?url=https://twitter.com/x/status/' . $tweet_id);
        $oembed = json_decode($oembed_j);

        $twitter = new Twitter;
        $twitter->url = $oembed->url;
        $twitter->author_name = $oembed->author_name;
        $twitter->author_url = $oembed->author_url;
        $twitter->html = $oembed->html;
        $twitter->width = $oembed->width;
        $twitter->height = $oembed->height;
        $twitter->type = $oembed->type;
        $twitter->cache_age = $oembed->cache_age;
        $twitter->provider_name = $oembed->provider_name;
        $twitter->provider_url = $oembed->provider_url;
        $twitter->version = $oembed->version;
        $twitter->save();
    }
}

}

错误:

"(1/1) FatalErrorException
Cannot use object of type stdClass as array

in TwitterController.php (line 27)"

1 个答案:

答案 0 :(得分:1)

因为$tweets是一个具有statuses属性的对象,所以你需要像这样迭代它:

foreach ($tweets->statuses as $tweet)