2

This is the following JSON Structure over which I m trying to iterate

{
   "AS":{
      "Query":"vi",
      "FullResults":1,
      "Results":[
         {
            "Type":"AS",
            "Suggests":[
               {
                  "Txt":"videos",
                  "Type":"AS",
                  "Sk":""
               },
               {
                  "Txt":"vipjatt",
                  "Type":"AS",
                  "Sk":"AS1"
               },
               {
                  "Txt":"vit",
                  "Type":"AS",
                  "Sk":"AS2"
               },
               {
                  "Txt":"vijaya bank",
                  "Type":"AS",
                  "Sk":"AS3"
               },
               {
                  "Txt":"videocon d2h",
                  "Type":"AS",
                  "Sk":"AS4"
               },
               {
                  "Txt":"visarev",
                  "Type":"AS",
                  "Sk":"AS5"
               },
               {
                  "Txt":"vijaya karnataka",
                  "Type":"AS",
                  "Sk":"AS6"
               },
               {
                  "Txt":"video songs",
                  "Type":"AS",
                  "Sk":"AS7"
               }
            ]
         }
      ]
   }
}

And this is the code I m using to iterate over it, and trying to access the "Txt" property

$data = $info->get($url);
$content = json_decode($data);
$i = 0;
foreach($content->AS->Results as $item) {
$each = $item->Suggests[$i]->Txt;
    $i++;
    echo $each;
}

But I only get the access of the first appearance of "Txt" property. Whats wrong with my code ? Why isint it printing every appearance of the "Txt" property??

1 Answer 1

3

You are iterating over the AS->Results items, of which there is exactly one. You want to iterate over the Suggests array directly:

foreach ($content->AS->Results[0]->Suggests as $item) {
    echo $item->Txt;
}

I don't know if there could be more than one item in the Results array. Perhaps you need to first iterate over them to pick out the right Suggests item to iterate over.

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.