【问题标题】:How to access JSON array with PHP如何使用 PHP 访问 JSON 数组
【发布时间】:2015-06-26 15:23:36
【问题描述】:

我正在使用 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/"
},

我可以通过使用标准 json_decode 访问大部分信息,然后使用 for 循环遍历项目,但由于某种原因,我在访问返回的平台数组时遇到问题。我正在尝试获取这样的平台名称:

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

但这样做时我总是会收到“未定义索引”错误。我在这里做错了什么?

【问题讨论】:

标签: php arrays json undefined-index


【解决方案1】:

platforms里面还有一个维度,需要再添加一个索引:

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

旁注:上面的代码只是直接指向索引零。如果该深度内还有更多内容,则在其中添加另一个迭代:

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

【讨论】:

  • 打败我这么多;-D
  • 呸,早该知道事情会这么简单。非常感谢!
  • @DrWatson 我很高兴这有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
相关资源
最近更新 更多