0

I have the following JSON:

{
  "stars":5,
  "numberOfReviews":{
    "total":1179,
  }
}

and the following PHP:

$json = file_get_contents('url-of-json');
$obj = json_decode($json);
print $obj->stars;

This prints 5 as expected. How do I print the "total" value of 1179 from the second level in the array's hierarchy?

I've been unable to find an explanation on how to achieve this. Here's some example of what I've been trying so far:

print $obj->total
print $obj->{'numberOfReviews', 'total'}
print $obj->['numberOfReviews']['total']
print $obj->numberOfReviews{'total'}
print $obj->[1]['total']
print $obj->numberOfReviews[0]total
print $obj->total[1]
NuclearApe
  • 573
  • 2
  • 6
  • 16
  • 1
    I think you've over-thinking this, possibly because you're looking for how to extract information from an array. This is simply two nested objects, so the syntax you need is just `$obj->numberOfReviews->total` – iainn Jul 19 '18 at 11:30
  • 1
    Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – iainn Jul 19 '18 at 11:30
  • One thing is that the JSON isn't valid, need to remove the comma at the end of `"total":1179,` – Nigel Ren Jul 19 '18 at 11:35

2 Answers2

1

$obj->numberOfReviews->total; Or add second parameter to json_decode with true value, and use it as array.

Michał
  • 51
  • 4
1

$obj->numberOfReviews is an \stdClass object too, so try it with $obj->numberOfReviews->total

l-x
  • 1,521
  • 9
  • 17