0

I fetched location:[] from monogodb and then encoded it in json and printed it on the screen. Here is the output:

{"57237036d89c45e1e3fda94e":{"_id":{"$id":"57237036d89c45e1e3fda94e"},"location":[33.7715,72.7511]}}

Now the problem is that I'm trying to get only location from this JSon so I decoded it. Here is the code:

  echo $arr= json_encode(iterator_to_array($cursor));
  $j= json_decode($arr,true);
  var_dump( $j->location); 

var_dump is returning null. Moreover it displays the following error

Trying to get property of non-object 

PS: I know this question has been asked a lot of times but I couldn't find a solution.

puffles
  • 352
  • 2
  • 5
  • 23
  • should be `json_decode($arr);` or `json_decode($arr,false);` check [json_decode](http://php.net/manual/en/function.json-decode.php) Manual – bansi Apr 30 '16 at 06:03
  • tried it. Still returns null and the error is Undefined property: stdClass::$location – puffles Apr 30 '16 at 06:06
  • Can you print_r($j) and check what value in $j. – Sk_ Apr 30 '16 at 06:09
  • @Sk_ This is what it prints:: object(stdClass)[6] public '57237036d89c45e1e3fda94e' => object(stdClass)[7] public '_id' => object(stdClass)[8] public '$id' => string '57237036d89c45e1e3fda94e' (length=24) public 'location' => array (size=2) 0 => float 33.7715 1 => float 72.7511 – puffles Apr 30 '16 at 06:18
  • I want to get location from this one – puffles Apr 30 '16 at 06:18

1 Answers1

0

$j->location is still not valid. you can get the location in the following 2 methods

your location is $j->57237036d89c45e1e3fda94e->location

$arr = '{"57237036d89c45e1e3fda94e":{"_id":{"$id":"57237036d89c45e1e3fda94e"},"location":[33.7715,72.7511]}}';
$j= json_decode($arr);
$x = '57237036d89c45e1e3fda94e'; 
var_dump( $j->$x->location); 
// if you don't want to declare $x
var_dump( $j->{'57237036d89c45e1e3fda94e'}->location); 

or using array method

$j = json_decode($arr, true);
var_dump( $j['57237036d89c45e1e3fda94e'][location]);
bansi
  • 55,591
  • 6
  • 41
  • 52