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

时间:2015-03-18 03:25:35

标签: php arrays object multidimensional-array instagram

我目前正在开展一个项目,在这个项目中,用户的关注者会在一个类似于此处的数组中提供给我: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小时的故障排除,现在我正在寻找你们的指导。我知道有很多关于相同错误的问题,但是没有一个包含像这样的嵌套数组,所以我有点迷失。

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

1 个答案:

答案 0 :(得分:2)

您可以使用:

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