如何访问嵌套数组:不能将 stdClass 类型的对象用作数组

How access to Nested Arrays: Cannot use object of type stdClass as array

我目前正在做一个项目,用户的关注者在一个数组中提供给我,如下所示:http://pastebin.com/304iPm4L

数组:

object(stdClass)#2 (3) { 
["pagination"]=> object(stdClass)#3 (2) 
    { 
    ["next_url"]=> string(146) "DATA"
    ["next_cursor"]=> string(13) "DATA" 
    } 
["meta"]=> object(stdClass)#4 (1) 
    { 
    ["code"]=> int(200) 
    } 
["data"]=> array(9) 
    { 
    [0]=> object(stdClass)#5 (4) 
        { 
        ["username"]=> string(7) "twurked" 
        ["profile_picture"]=> string(106) "https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-19/11055444_697242820403478_108851570_a.jpg" 
        ["id"]=> string(9) "307611076" 
        ["full_name"]=> string(20) "#twurked For Reposts" 
        } 
    [1]=> object(stdClass)#6 (4) 
        {
         ["username"]=> string(12) "itsmarziapie" 
        ["profile_picture"]=> string(107) "https://igcdn-photos-b-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-19/10735354_634448103338889_1219780551_a.jpg" 
        ["id"]=> string(9) "415505158" 
        ["full_name"]=> string(15) "Marzia Bisognin" 
        } 
    [2]=> object(stdClass)#7 (4) 
        { 
        ["username"]=> string(11) "briankgrubb" 
        ["profile_picture"]=> string(107) "https://igcdn-photos-d-a.akamaihd.net/hphotos-ak-xpa1/t51.2885-19/10518270_1508565329429347_713909002_a.jpg" 
        ["id"]=> string(8) "28307611" 
        ["full_name"]=> string(11) "Brian Grubb" 
        } 
    [3]=> object(stdClass)#8 (4) 
        { 
        ["username"]=> string(16) "redbulladventure" 
        ["profile_picture"]=> string(106) "https://igcdn-photos-d-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-19/11007825_728249480627075_348216069_a.jpg" 
        ["id"]=> string(10) "1721797894" 
        ["full_name"]=> string(18) "Red Bull Adventure" 
        } 
     } 
}

我想做的是获取每个用户的 username 值并将其输出到屏幕。

所以,我想到的是我可以轻松地(或者我认为......)循环我的结果并输出每个嵌套数组中的 username 值。

我使用了这个代码:

$i = 1;
while ($i <= 10) {
    $instagram->getUserFollows('self',10)->data[$i]["username"]; 
    echo "<br/>";
    $i++;
}

$instagram->getUserFollows('self',10) 数组,就是你在 pastebin 中看到的。通过查看我的嵌套数组,我似乎需要一个数字,然后 ["username"] 才能访问每个用户名。

理论上,$instagram->getUserFollows('self',10)->data["1"]["username"];应该输出itsmarziapie

但是,当我 运行 上面的代码时,我得到了这个:

Cannot use object of type stdClass as array

这个错误是什么意思,为什么我不能将我的 username 数据循环显示到屏幕上??

至此,我已经进行了大约 2.5 小时的故障排除,现在正在寻求你们的指导。我知道有很多关于相同错误的问题,但是 none 其中包括像这个一样的嵌套数组,所以我有点迷茫。

感谢您帮我指出正确的方向:)

你可以使用这个:

//You request 10 objects but you don't know if there are really 10
    $info = $instagram->getUserFollows('self',10);

//How many objects?
    $qty = count($info->data);

/* You can't assume that there are 10 objects (I refer to your code, 
 * you have 9 objects and you try to access to 10 objects)    
 */
    for($i = 0; $i < $qty ; $i++) { 
      echo $info->data[$i]->username . "<br>";
    }