如何访问对象Twitter API中的对象?

时间:2018-09-11 03:52:59

标签: php object twitter

我已经开始使用Twitter API和亚伯拉罕的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;

但是我真的不知道如何对这些嵌套数据进行排序。如何浏览此数据结构并访问其中的不同部分?

1 个答案:

答案 0 :(得分:0)

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

//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中使用ArraysObjects

相关问题