StudioTime
StudioTime

Reputation: 23999

JSON Parse empty results

I have the following example 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"
               }
            ]
         }

There will be multiple Merchant names I want to print but getting blank result (I am quite new to JSON parsing)

Here's what I'm trying:

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

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

Is this the correct method?

UPDATE

As has been correctly pointed out (I didn't add enough example) 'groups' is an array, so, I've changed to the following but still no joy:

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

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

Upvotes: 0

Views: 58

Answers (1)

Mifeet
Mifeet

Reputation: 13648

Value under groups index is an array and you miss the index to this array. Maybe something like this would help:

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

(depending on what can be in the groups array and what you want to do about it).

Update Now there is conversely too much indirection to the groups array :). Try this:

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

Upvotes: 1

Related Questions