November 23, 2010

How could I loop through this json object in php file?

Question by XCeptable

I have converted an xml object returned from a php function into json format to send it to js file like.

function searchResults($q) { ...
    $xml = simplexml_load_string($result);
    return json_encode($xml); }

I receive/use it in js like

  var msg_top = "<"+"?php echo searchResults('windows');"+"?"+">";

Then I receive it back in php & decoded.

      $json = $_POST['msg_top'];
      $msg = json_decode($json);

Now how do I loop through it to get all values of its certain properties that I could have get from xml object(which I converted into json). This is how I loop over xml object to get all values of its certain properties:

   foreach ($xml->entry as $status) {
   echo $status->author->name.''.$status->content);
   }

How do I get all those values from decoded json object $msg?
EDITED
I tried in same HTML where I am using js to receive & POST php search function data via ajax, I tried following code to loop through json in php. But it did not show anything.

$obj = searchResults(testword);//serach function returns json encoded data
$obj = json_decode($obj, true);
$count = count($obj);  
for($i=0;$i<$count;$i++)
{
echo $obj[$i][content];}// using xml for it, I get ouput like foreach ($xml3->entry as 
                       // $status) {status->content}

Answer by Yorirou

By default, json_decode returns an stdClass. stdClass-es can be used the same way as associative arrays with foreach.

Alternatively, you can ask json_decode to return an associative array:

$array = json_decode($_POST['foo'], TRUE);

Answer by Starx

I think you have to use $msg for the FOR LOOP as it is the array.

Try to see what it hold using this

echo "<pre>".print_r($msg)."</pre";
//And if you see the correct array structure
foreach($msg as $key=>$value) {
  //do your things
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!