如何使用php中的字符串路径访问嵌套的stdclass?

如何使用php中的字符串路径访问嵌套的stdclass?,php,stdclass,Php,Stdclass,假设您有一个变量$a,它是包含嵌套Stdclass等的Stdclass,如下所示: <?php $json = '{ "foo": { "foo":{ "foo":"bar" } } }'; $a = json_decode($json); $b="foo.foo.foo"; print_r($a->foo->foo->foo); print_r($$b}); ?> 现在在变量$b中,我有了想要访问的路径 有没有办法

假设您有一个变量
$a
,它是包含嵌套Stdclass等的Stdclass,如下所示:

<?php
$json = '{ "foo": {
    "foo":{
            "foo":"bar"
    }
} }';
$a = json_decode($json);
$b="foo.foo.foo";

print_r($a->foo->foo->foo);
print_r($$b});

?>

现在在变量
$b
中,我有了想要访问的路径


有没有办法告诉PHP获取该路径的值?

在点上分解,然后迭代,使用每个段作为对象属性

$path = explode('.', $b);

$current = $a;
foreach ($path as $segment) {
    $current = $current->$segment;
}

var_dump($current);   // bar
如果路径包含未正确映射到对象属性的段,则会收到未定义的属性通知,并以
null
值结束


请注意,这仅适用于嵌套对象。如果您的输入JSON包含任何级别的数组,这将无法处理它,您需要更复杂的东西。

PHP不支持点语法。你为什么要这么做?