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

how to acess nested STDClasses with the string path in php?

假设您有一个变量 $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 包含任何级别的数组,这将无法处理,您需要更复杂的东西。