dousha1873 2018-09-11 03:52
浏览 125

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

I've started working with the Twitter API and Abraham's TwitterOAuth wrapper to retrieve Twitter data, but I can't figure out how to access objects within the array returned. The data is structured like so:

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)

There are many more layers, as tweets are actually extremely complex. I can access the first few pieces of data before the entities object, but, how do I access these sub-layers? Say, for instance, I want to access the screen name of the user. I have tried like so:

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

But I really have no idea to sort through this nested data. How do I navigate this data structure and access the different pieces of it?

  • 写回答

1条回答 默认 最新

  • douliedai4838 2018-09-11 04:04
    关注

    First, the response is an array. So to get the first item from the array,

    //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;
    

    If you wanted to iterate through an array of tweets,

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

    Overall a fairly broad question. You should look into working with Arrays and Objects in PHP.

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站