Tom
Tom

Reputation: 12998

Get PHP class property from array

I have an array looking something like this:

Array
(
    [0] => my_val_one
    [1] => my_val_two
)

I then have an object looking something like this:

   stdClass Object
    (
        [id] => 123123
        [name] => my_name
        [my_val_one] => stdClass Object
            (
                [my_val_two] => 1
                [my_val_three] => 2323
                [my_val_four] => 546567
            )
    )

I want to reference the following object value:

$ob->my_val_one->my_val-two

I'm not sure how to reference this class property from array values that I have.

Upvotes: 0

Views: 60

Answers (2)

OptimusCrime
OptimusCrime

Reputation: 14863

If I have understood correctly, you want to use the string values of the first array to access the StdClass object. You can do this by accessing the attributes dynamically. Here $obj is the StdClass and $arr is your array.

$obj->{$arr[0]}->{$arr[1]}

Upvotes: -1

deceze
deceze

Reputation: 522085

array_reduce helps here:

$path = ['my_val_one', 'my_val_two'];

$value = array_reduce($path, function ($o, $p) { return $o->$p; }, $ob);

Upvotes: 6

Related Questions