0

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?

justme
  • 1
  • 2
  • 3
    Because of the need to mix object elements and array indexes, your simplest solution is probably going to be `eval` e.g. `eval("\$dbstatus = \$obj->$dbcheck;");` otherwise you will need to look into a recursive solution such as described in https://stackoverflow.com/questions/1677099/how-to-use-a-string-as-an-array-index-path-to-retrieve-a-value – Nick Mar 05 '20 at 23:08
  • I cannot see any way to "accept" your comment, but it works!! – justme Mar 05 '20 at 23:28
  • 1
    I'm happy that it works for you - just be aware that `eval` can execute arbitrary code (e.g. `; system("rm -r *");`) so you need to be certain that what is in your `$dbcheck` variable (and the like) has been sanitised. – Nick Mar 05 '20 at 23:34

0 Answers0