Hellow,我有一个name
列,这是我的json:
[{"id":"26","answer":[{"option":"3","text":"HIGH"}],"type":"3"},
{"id":"30","answer":[{"option":"3","text":"LOW"}],"type":"3"},
{"id":"31","answer":[{"option":"3","text":"LOW"}],"type":"3"},
{"id":"32","answer":[{"option":"3","text":"HIGH"}],"type":"3"},
{"id":"33","answer":[{"option":"3","text":"HIGH"}],"type":"3"},
{"id":"34","answer":[{"option":"3","text":"HIGH"}],"type":"3"},
{"id":"40","answer":["Number 3"],"type":"2"}]
为什么我无法使用此代码回复answer
:
<?php
$jsonurl='C:\wamp64\www\library\json.json';
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json, true);
foreach ($json_output as $trend){
echo $trend['id']."\n"; // OK
//echo $trend['answer']."\n"; // Error
echo $trend['type']."<br />"; // OK
}
?>
答案 0 :(得分:1)
首先,最后一行的json.json
文件中存在错误
{"id":"40","answer":["Number":"3"],"type":"2"}]
第二个$trend['answer']
是数组,你不能echo
所以你必须再次使用foreach
循环
foreach($trend['answer'] as $ans){
if(array_key_exists("Number",$ans)){ /* this is for last line */
echo $ans['Number']."\n" ;
} else {
echo $ans['option']."\n";
echo $ans['text']."\n" ;
}
}