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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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}
How to&Answers:

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:

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
}