【发布时间】:2023-03-26 19:10:01
【问题描述】:
我的左手有这个“钥匙”:
localisation.adresse.commune.id
和许多其他像这个一样的值,它们是动态的(我不能在我的代码中使用它们,因为我不知道它们会是什么)。
另一方面,我有一个这样的数组(来自一个 json 解码):
Array
(
[localisation] => Array
(
[adresse] => Array
(
[adresse1] => Le Chatelard
[codePostal] => 42820
[etat] => France
[commune] => Array
(
[id] => 16418
)
)
)
)
我无法列出我要利用的所有“密钥”,所以我需要自动获取 $object['localisation']['adresse']['commune']['id' 的值].
我试过了,但它不起作用:
$test['localisation']['adresse']['commune']['id'] = 16418 ;
$var = '$test[\'localisation\'][\'adresse\'][\'commune\'][\'id\']' ;
echo $var ; // $test['localisation']['adresse']['commune']['id']
var_dump($$var) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']
var_dump(${$var}) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']
我想它正在寻找一个复杂名称的简单变量,而不是查看多维数组,但我不知道我该怎么做......
感谢您的帮助!
【问题讨论】:
-
你需要通过 json_decode 解码数组中的那个 json 字符串
-
我已经做到了,使用 \GuzzleHttp\Utils::jsonDecode($objet, true);。这不是真正的问题,我可以从问题中删除 json 部分,我已经有一个关联数组:
Array ( [localisation] => Array ( [adresse] => Array ( [adresse1] => Le Chatelard [codePostal] => 42820 [etat] => France [commune] => Array ( [id] => 16418 ) ) ) )
标签: php arrays recursion dynamic-programming