If I know the path of an element in the array, how do I get the value of this element?
The following code reports an error, how to solve it? Does anyone have any good ideas?
$m = ['a'=>['b'=>['c'=>'@@@@@']]];
$x = 'a.b.c';
$y = str_replace('.','\'][\'',$x);
$y = 'm[\''.$y.'\']';
echo $$y;
An error will be reported:
Notice: Undefined variable: m['a']['b']['c'] in /web/root/index.php on line 9
Dynamic variable names are only valid for variables, not array elements.
'm["a"]["b"]["c"]'
Even if $ is added in front, the entire string will be regarded as a variable, and naturally it cannot be found.You can simply use a loop
?First of all, the variable $y after the echo you printed has one more
$
符号,其次如果你想获取@@@@@
,直接$m['a']['b']['c']
Actually, what you wrote is correct, don’t rush to ask, take a look at your code
Personally, I think that when facing this kind of problem, we should consider using recursion to deal with it instead of using string replacement.
If you use laravel framework,