简体   繁体   English

如何使用PHP访问JSON数组

[英]How to access JSON array with PHP

I'm using the Giantbomb API, which returns results like so; 我正在使用Giantbomb API,它返回的结果是这样的;

{
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. 我可以使用标准的json_decode来访问最多的信息,然后使用for循环遍历各项,但是由于某些原因,我在访问返回的平台数组时遇到了问题。 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: platforms内部还有另一个维度,您需要添加另一个索引:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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