简体   繁体   中英

How to access JSON array with PHP

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?

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'];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM