Here is the object I decode from JSON in PHP:
php > var_dump($v);
object(stdClass)#9 (1) {
["objects"]=>
object(stdClass)#10 (2) {
["16"]=>
object(stdClass)#14 (2) {
["id"]=>
int(16)
["name"]=>
string(8) "Object 1"
}
["32"]=>
object(stdClass)#11 (2) {
["id"]=>
int(20)
["name"]=>
string(8) "Object 2"
}
}
}
php > $rc = new \ReflectionClass($v);
php > var_dump($rc);
object(ReflectionClass)#17 (1) {
["name"]=>
string(8) "stdClass"
}
php > var_dump($rc->getProperties());
array(0) {
}
As you can see, ReflectionClass fails to detect any of the properties. I cannot do $v->objects->32
, because PHP does not allow numeric properties. I also cannot decode to an associative array, because that would break JSON handling in other parts of my system.
The simpliest way is to use the second parameter of json_decode and set it to true. Using this method, you can access the vars like in any other associative array
$v = json_decode($data, true);
$value = $v['objects']['32']
if you cant change the json_decode call, you can use the following syntax to access the var
$v = json_decode('{"objects":{"16":{"id":16,"name":"Object 1"},"32":{"id":20,"name":"Object 2"}}}');
var_dump($v->objects->{'16'});
and even
$name = '16';
var_dump($v->objects->{$name});