JSON解析空结果

时间:2014-04-01 11:48:19

标签: php

我有以下示例JSON:

{
productAPI: {
  status: 200,
  message: "OK",
  version: 3,
  products: {
    grouped: {
      matches: 773949,
      groups: [
        {
          doclist: {
            start: 0,
            numFound: 385957,
            docs: [
              {
                merchant: "Amazon",
                currency: "GBP"
               }
            ]
         },
         doclist: {
            start: 0,
            numFound: 885957,
            docs: [
              {
                merchant: "Ebay",
                currency: "GBP"
               }
            ]
         }

我想要打印多个商家名称但是得到空白结果(我对JSON解析很新)

这是我尝试的内容:

$prodList=$prodList['productAPI']['products']['grouped']['groups']['doclist']['docs'];

foreach ($prodList as $element){
    echo $element['merchant'];
}

这是正确的方法吗?

更新

正如已经正确指出的那样(我没有添加足够的例子)' group'是一个数组,所以,我改变了以下但仍然没有喜悦:

$prodList=$prodList['productAPI']['products']['grouped']['groups'];

$i=0;
foreach ($prodList as $element){
    echo $element[$i]['doclist']['docs']['merchant'];
    $i++;
}

1 个答案:

答案 0 :(得分:1)

groups索引下的值是一个数组,你错过了这个数组的索引。也许这样的事情会有所帮助:

$prodList=$prodList['productAPI']['products']['grouped']['groups'][0]['doclist']['docs']; 

(取决于groups数组中的内容以及您想要做的事情)。

<强>更新 现在反过来对groups数组:)的间接过多。试试这个:

$prodList=$prodList['productAPI']['products']['grouped']['groups'];
foreach ($prodList as $element){
    $docs = $element['doclist']['docs'];
    foreach ($docs as $doc) {
        echo $doc['merchant'];
    }
}