Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/JSON Array - From iTunes

Tags:

json

php

I've just started out learning PHP/JSON and I've kind of worked out how to output an array from an json file. My aim is to output all the album titles in <li>'s (in this case they are called collectionName in the json file). I think I maybe going about it the wrong way though.

$artistId = '644708';    
$otherAlbumsURL = 'http://itunes.apple.com/lookup?id='. $artistId .'&entity=album';
$a = (array)json_decode(file_get_contents($otherAlbumsURL));
var_dump($a);
like image 349
BCLtd Avatar asked Mar 28 '26 16:03

BCLtd


1 Answers

If you want an array, just use:

$a = json_decode(file_get_contents($otherAlbumsURL), true);
var_dump($a);

Setting the second parameter in json_decode to TRUE will give you an associative array instead of an object.

Judging from the response of the URL, you'll need to loop through the result like this in order to get any available collection names (the first array element doesn't contain a collection name because it is information about the artist. i.e. it isn't an album):

$artistInfo = $a['results'][0]; //Assign artist info to its own variable.
unset($a['results'][0]); //Delete artist info from the array.

//Loop through the results
foreach($a['results'] as $result){
    //$result['collectionName'] has the collection name.
    echo $result['collectionName'] . '<br>';
}
like image 142
Wayne Whitty Avatar answered Mar 30 '26 05:03

Wayne Whitty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!