0

Considering I have a string entity.field_one.field_two.value, how can I take this and construct a selection on an existing PHP object? Based on the string above I want to construct:

$output = $entity->field_one->field_two->value;

I'm aware that I can use variables like $entity->{$var1} but considering I don't know how many dots there are going to be, I need to find a way to construct the whole thing dynamically.

Any help appreciated!

Chris
  • 1,429
  • 4
  • 18
  • 34

1 Answers1

1

How to access and manipulate multi-dimensional array by key names / path? shows how to do this for nested array elements. You can use a similar method for object properties.

function get($path, $object) {
    if (is_string($path)) {
        $path = explode('.', $path);
    }
    $temp =& $object;

    foreach($path as $key) {
        $temp =& $temp->{$key};
    }
    return $temp;
}

echo get("field_one.field_two.value", $entity);

Barmar
  • 669,327
  • 51
  • 454
  • 560