假设我的JSON是这样的:
{
"achievement": [
{
"title": "All Around Submitter",
"description": "Get one piece of content approved in all six areas.",
"xp": 500,
"level_req": 1
},
{
"title": "World-wide Photo Journalist",
"description": "Get one photo approved in all six areas.",
"xp": 500,
"level_req": 1
},
{
"title": "Ready for Work",
"description": "Sign up and get validated",
"xp": 50,
"level_req": 1
},
{
"title": "Asian Pride",
"description": "Get ten pieces of content approved to a club in an Asian nation.",
"xp": 1500,
"level_req": 1
}
]
}
我的PHP代码是这样的,所以我加载了json文件......:
<?php
$string = file_get_contents("achievements.json");
$json_a=json_decode($string,true);
foreach ($json_a as $key => $value){
echo $value[0]['title'] . " <br />";
}
?>
然而它只放出第一个数组。我知道。只有1.但foreach
循环怎么样?为什么不是每行循环?
答案 0 :(得分:7)
您正在遍历顶级数组,该数组只有一个键:achievement
相反,你应该
foreach ($json_a['achievement'] as $key => $value){
echo $value['title'] . " <br />";
}
提示:[0]
是一种特定的代码气味。
答案 1 :(得分:1)
这里试试这个
$string = file_get_contents("achievements.json");
$json_a=json_decode($string,true);
foreach ($json_a['achievement'] as $key => $value){
echo $value['title'] . " <br />";
}
你正在循环你的顶级数组,但在解析你的json之后你会得到:
array(1) {
["achievement"]=>
array(4) {
//your other arrays
}
}
答案 2 :(得分:0)
它无效,因为您循环的数组只有一个键achievements
,这是您json_decode()
返回的数组,给定您当前的json。循环一遍,你会得到你想要的东西:
foreach ($json_a['achievement'] as $key => $value){
echo $value['title'] . "<br />";
}