Cody Raspien
Cody Raspien

Reputation: 1845

JSON sub array - PHP decode

I have a JSON feed and within the feed, there is an array inside the feed, I can output everything above the array correctly.

JSON feed output: http://pastebin.com/pxiFVm1d

Code used to output:

$jsonurl = "LINK to feed";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->results as $results )
{
    echo "{$results->name}.<br />";
}

How do I output the photo_rerence which is part of the array (see pastebin)?

Upvotes: 0

Views: 2314

Answers (3)

Mateusz Drankowski
Mateusz Drankowski

Reputation: 101

Just to add to what arkascha said, if you want to use it as an array, you will need to add the second param on your json_decode:

$json_output = json_decode($json, TRUE); 

Refer to php.net/json_decode for details.

Upvotes: 0

elMarquis
elMarquis

Reputation: 7730

If there's the possibility that there might be multiple photos you could do:

$json_output = json_decode($json);
foreach ( $json_output->results as $results )
{
    foreach($results->photos as $photo) {
        echo $photo->photo_reference;
    }
}

Or if you only ever want to grab from the first one in the array just do:

$json_output = json_decode($json);
foreach ( $json_output->results as $results )
{
   echo $results->photos[0]->photo_reference;
}

Upvotes: 1

arkascha
arkascha

Reputation: 42935

Either you make a "deep pick": $results['photos']['photo_reference'], or take a look at phps array_walk() function which allows you to "search" through the array in a recursive manner.

Upvotes: 0

Related Questions