0

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++;
}
3
  • 1
    $prodList where its defined? Did you json_decode()? Commented Apr 1, 2014 at 11:53
  • @RahilWazir Yes, its defined to bring in the data: $prodList = json_decode(file_get_contents('URL_HERE'),true); Commented Apr 1, 2014 at 12:16
  • Post your full JSON response please. Commented Apr 1, 2014 at 12:34

1 Answer 1

1

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'];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.