如何解析php中的复杂数组

时间:2015-01-12 00:06:34

标签: php arrays

我有$ photo_array,我想获得一个特定的网址。

这是我的PHP ..我很确定我做得不对:

$photo_array = $user_photos->asArray(); 

foreach($arr as $key => $value)
{
    $url = $photo_array["data"]->$key->images->["0"]->source;
    echo $url."<br>";
}

这是我的数组的副本...请参阅箭头以查看我想要的值。 并且foreach必须应用于第一个[0] ...所以我只需要每个键中的1个URL

Array
(
[data] => Array
    (
        [0] => stdClass Object         <<<<<  FOREACH  applies to this key HERE
            (
                [id] => 123
                [created_time] => 2013-04-21T22:22:33+0000
                [from] => stdClass Object
                    (
                        [id] => 123
                        [name] => name
                    )

                [height] => 479
                [icon] => https://fbstatic-a.akamaihd.net/rsrc.php/v2/yz/r/StEhvv3RhPvjk.gif
                [images] => Array
                    (
                        [0] => stdClass Object
                            (
                                [height] => 1365
  ***THIS IS WHAT I WANT >>>>>  [source] => https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-8/9034014_10151555782563_1289220490_o.jpg
                                [width] => 2048
                            )

                        [1] => stdClass Object
                            (
                                [height] => 960
                                [source] => https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-8/p960x960/9032201_101513582563_1480490_o.jpg
                                [width] => 1440
                            )

                        [2] => stdClass Object
                            (
                                [height] => 720
                                [source] => https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xpf1/t31.0-8/p720x720/903401_101513782563_148970_o.jpg
                                [width] => 1080
                            )

                    )

                [link] => https://www.facebook.com/photo.php?fbid=10151351263&set=a.41902562.210698.6182562&type=1
                [updated_time] => 2014-11-24T22:43:04+0000
                [width] => 720

我该怎么做...谢谢

2 个答案:

答案 0 :(得分:0)

你错了。 dataarray,而不是object。这应该有效:

$url = $photo_array["data"][$key]->images['0']->source;

同样适用于images。它是array而不是object


  • 访问数组时,您可以将索引(即[0])直接应用于数组名称。
  • 访问对象时,您可以通过->访问密钥(索引)。

答案 1 :(得分:0)

foreach ($photo_array['data'] as $photo) {
    // iterate all images:
    foreach ($photo->images as $image) {
        echo $image->source;
    }

    // or just the first one:
    echo $photo->images[0]->source;
}