首页 > 解决方案 > 如何访问对象 Twitter API 中的对象?

问题描述

我已经开始使用 Twitter API 和 Abraham 的TwitterOAuth包装器来检索 Twitter 数据,但我不知道如何访问返回的数组中的对象。数据的结构如下:

array(1) { [0]=> object(stdClass)#462 (24) { 
["created_at"]=> string(30) "Tue Sep 11 03:30:54 +0000 2018" 
["id"]=> int(120823024720) 
["id_str"]=> string(19) "1268383623782373" 
["text"]=> string(141) "RT @user: tweet tweet tweet tweet tweet" 
["truncated"]=> bool(false) 
["entities"]=> object(stdClass)#463 (4) { 
    ["hashtags"]=> array(0) { } 
    ["symbols"]=> array(0) { } 
    ["user_mentions"]=> array(1) { 
        [0]=> object(stdClass)#464 (5) { 
        ["screen_name"]=> string(6) "user" 
        ["name"]=> string(3) "username" 
        ["id"]=> int(12361328) 
        ["id_str"]=> string(8) "12342312" 
        ["indices"]=> array(2) { 
            [0]=> int(3) 
            [1]=> int(10) } } } 
        ["urls"]=> array(0) { } } 
        ["source"]=> string(82) "Twitter for iPhone" 
        ["in_reply_to_status_id"]=> NULL 
        ["in_reply_to_status_id_str"]=> NULL 
        ["in_reply_to_user_id"]=> NULL 
        ["in_reply_to_user_id_str"]=> NULL 
        ["in_reply_to_screen_name"]=> NULL 
        ["user"]=> object(stdClass)#465 (42)

还有更多层,因为推文实际上非常复杂。我可以访问对象之前的前几条数据entities,但是,我如何访问这些子层?比如说,我想访问用户的屏幕名称。我试过这样:

$data->entities->user_mentions->screen_name;

但我真的不知道对这些嵌套数据进行排序。如何导航此数据结构并访问它的不同部分?

标签: phpobjecttwitter

解决方案


首先,响应是一个数组。所以要从数组中获取第一项,

//get first item
$tweet = $data[0];

//user_mentions is also an array
$mention = $tweet->entities->user_mentions[0];

//now you can access the screen name with
$mention->screen_name;

如果你想遍历一系列推文,

foreach( $data as $tweet ) {
    $mention = $tweet->entities->user_mentions[0];
    echo $mention->screen_name;
}

总的来说是一个相当广泛的问题。您应该研究在 PHP 中使用数组对象。


推荐阅读