如何使用 PHP 访问 JSON 数组
How to access JSON array with PHP
我正在使用 Giantbomb API,returns 结果是这样的;
{
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'];
但我这样做时总是会遇到 "Undefined Index" 错误。我在这里做错了什么?
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'];
}
}
我正在使用 Giantbomb API,returns 结果是这样的;
{
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'];
但我这样做时总是会遇到 "Undefined Index" 错误。我在这里做错了什么?
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'];
}
}