puffles
puffles

Reputation: 372

how to get _id from json decode

Here is my json which I get from mongodb:

object(stdClass)[6]
  public '572453d55addfab49090ea71' => 
    object(stdClass)[7]
      public '_id' => 
        object(stdClass)[8]
          public '$id' => string '572453d55addfab49090ea71' (length=24)
      public 'location' => 
        array (size=2)
          0 => float 24.8615
          1 => float 67.0099

In order to access location I have to use following statement in php

$lat= $j->{'572453d55addfab49090ea71'}->location[0]; 

I want to make it generic by first getting _id and then using the above statement. I have tried following statements which all return error:

 echo $arr= json_encode(iterator_to_array($cursor));
     echo var_dump(json_decode($arr));
$j = json_decode($arr,false);
     $lat = $j->_id->id;
    $lng = $j->id->location[1];

Kindly tell me how to solve this issue

Upvotes: 1

Views: 1521

Answers (1)

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

Use another parameter true with json_decode(), then you will get the result as php array format.

use the code below to print array and paste the result here, then i'll let you know how you can print your _id

$jsonDecode = json_decode($yourJson, true);
echo "<pre>"; print_r($jsonDecode);

Resulted array should be like this

 Array ( 
        [572453d55addfab49090ea71] =>
                 Array ( 
                        [_id] => 
                                Array ( 
                                        [$id] => 572453d55addfab49090ea71 
                                      )

                         [location] => Array ( [0] => 24.8615 [1] => 67.0099 ) 
                       ) 
        )

Finally use:

$_id = array_column($jsonDecode, '_id');
echo $_id[0]['$id'];

Upvotes: 1

Related Questions