echo json array VIA PHP

时间:2017-02-05 08:09:25

标签: php mysql json

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
  }  
?>

1 个答案:

答案 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" ;
      }
    }