search

Home  >  Q&A  >  body text

Dynamic path problem of an element of an array in php

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
世界只因有你世界只因有你2860 days ago544

reply all(6)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:11:31

    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

    $m  = ['a'=>['b'=>['c'=>'@@@@@']]];
    
    $x = 'a.b.c';
    $y = explode('.',$x);
    $z = $m;
    foreach ($y as $key => $value) {
        $z = $z[$value];
    }
    
    var_dump($z); 

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:11:31

    ?First of all, the variable $y after the echo you printed has one more $符号,其次如果你想获取@@@@@,直接$m['a']['b']['c']

    reply
    0
  • 迷茫

    迷茫2017-05-16 13:11:31

    Actually, what you wrote is correct, don’t rush to ask, take a look at your code

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:11:31

    Personally, I think that when facing this kind of problem, we should consider using recursion to deal with it instead of using string replacement.

    <?php
    
    $data = [
        'a'=>[
            'b'=>[
                'c'=>'@@@@@'
                ]
            ]
        ];
    
    $path = 'a.b.c';
    
    $arr = explode('.',$path);
    
    function test($arr, $data){
        if(array_key_exists($arr[0],$data)){
            if(count($arr) > 1){
                $key = array_shift($arr);
                return test($arr, $data[$key]);
            }else{
                return $data[$arr[0]];
            }
        }else{
            return null;
        }
    }
    
    var_dump(test($arr,$data));

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-16 13:11:31

    $m  = ['a'=>['b'=>['c'=>'@@@@@']]];
    $x = 'a.b.c';
    
    echo array_reduce(explode('.', $x), function($s, $i) { return $s[$i]; }, $m);

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 13:11:31

    If you use laravel framework,

    $m = [ 'a'=>['b'=>['c'=>'@@@@@' ]]];
    $x = 'a.b.c';
    $z = array_get($m,$x);
    return $z;

    reply
    0
  • Cancelreply