I've read in this post Get PHP class property by string, that I can access a property with a variable like - echo $obj->$prop. However my issue is a little different and I'm not finding the right answer for a nested property. The example listed shows 1 level deep. I need something that can work for 1 or more levels deep. My need is to access "status" dynamically with a variable.
$str = '{
"health" : {
"status" : "UP"
}
"db" : {
"postgres" : {
"status" : "UP"
}
}
"disk" : {
"status" : "UP"
}
}';
$healthcheck = "health->status";
or
$dbcheck = "disk->status";
or in some cases
$dbcheck = "db->postgres->status"
or in other cases
$dbcheck = "db->postgres[0]->status"
And I'm hoping to use the strings shown above to dynamically access the values.
But my code below fails:
$obj = json_decode( $str );
echo $obj->$healthcheck;
PHP Notice: Undefined property: stdClass::$health->status
I know the json structure exists, I'm just not finding the right way to access the sub element.
If I try it like the original post and change
// $healthcheck = "health->status";
$healthcheck = "health";
print_r( $obj->$healthcheck );
it works fine. Obviously I'm using print_r() since "health" is an object and "print" or "echo" will not print an object.
stdClass Object
(
[status] => UP
)
How can I access the nested properties?