如何解析嵌套的json数组

时间:2013-11-14 23:13:22

标签: php json

我有一个json,如下所示,

{
   "responseHeader":{
      "status":0,
      "QTime":1
   },
   "spellcheck":{
      "suggestions":[
         "goo",
         {
            "numFound":5,
            "startOffset":0,
            "endOffset":3,
            "suggestion":[
               "good",
               "googl",
               "goodby",
               "goos",
               "goodwil"
            ]
         },
         "collation",
         "good"
      ]
   }
}

我尝试了下面的PHP代码来获取建议中的元素列表,即好,谷歌,goodby,goos,善意

$myArray = json_decode($response, true);
foreach ($myArray['spellcheck']['suggestion'] as $doc) {
   echo $doc;
}

但是得到这个错误

Notice: Undefined index: suggestion in /Applications/XAMPP/xamppfiles/htdocs/ir/suggestions.php on line 9

如何获得建议的各个要素?

1 个答案:

答案 0 :(得分:1)

这只是一个拼写错误,“建议”你的数组索引缺少“s”(这是建议)

$myArray = json_decode($response, true);
foreach ($myArray['spellcheck']['suggestions'] as $doc) {
   echo $doc;
}