0

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.

4
  • 2
    can you explain a bit more, what you want to achieve? Commented Oct 3, 2017 at 13:10
  • 2
    How is the array related to the object (?). And why would you do my_val_one->my_val-two when these are two array values? That does not make any sense Commented Oct 3, 2017 at 13:11
  • Could you give us some background into why you need this, to begin with? Commented Oct 3, 2017 at 13:16
  • Considering your updated post, does $ob->my_val_one->my_val-two not work? Commented Oct 3, 2017 at 13:20

2 Answers 2

6

array_reduce helps here:

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

$value = array_reduce($path, function ($o, $p) { return $o->$p; }, $ob);
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on! That does exactly what I was looking for. Didn't know about array_reduce. I'll go off now and try to understand it!
-1

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]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.