1

I'm using the Giantbomb API, which returns results like so;

{
error: "OK",
limit: 100,
offset: 0,
number_of_page_results: 24,
number_of_total_results: 24,
status_code: 1,
results: [ 
{
expected_release_day: 8,
expected_release_month: 5,
name: "Project CARS",
platforms: [
{
  api_detail_url: "http://www.giantbomb.com/api/platform/3045-94/",
  id: 94,
  name: "PC",
  site_detail_url: "http://www.giantbomb.com/pc/3045-94/",
  abbreviation: "PC"
  },
 ],
site_detail_url: "http://www.giantbomb.com/project-cars/3030-36993/"
},

I can access the most information by using the standard json_decode, then iterating through the items using a for loop, but for some reason, I am having issues accessing the platforms array that is returned. I'm trying to get the name of a platform like so:

foreach($games['results'] as $item){
print $item['platforms']['name'];

but I always get "Undefined Index" errors when doing so. What am I doing wrong here?

DrWatson
  • 13
  • 2
  • `foreach($games['results']['platforms'] as $item){ print $item['name']; }`...? (Or do as [*Ghost answered ;-)*](http://stackoverflow.com/a/29738843/2518525)) – Darren Apr 20 '15 at 03:25
  • possible duplicate of [Iterating over a complex Associative Array in PHP](http://stackoverflow.com/questions/26007/iterating-over-a-complex-associative-array-in-php) – psiyumm Apr 20 '15 at 03:56

1 Answers1

4

There is still another dimension inside platforms, you need to add another index:

foreach($games['results'] as $item) {
    if(isset($item['platforms'][0]['name'])) {
        echo $item['platforms'][0]['name'];
    }
}

Sidenote: The code above just points out directly to index zero. If there's a lot more inside that depth, then you add another iteration inside:

foreach($games['results'] as $item) {
    foreach($item['platforms'] as $platform) {
        echo $platform['name'];
    }
}
Kevin
  • 41,694
  • 12
  • 53
  • 70