Access array using dynamic path

前端 未结 3 434
攒了一身酷
攒了一身酷 2020-12-11 05:58

I have an issue in accessing the array in php.

$path  = \"[\'a\'][\'b\'][\'c\']\";
$value = $array.$path;

In the above piece of code I hav

3条回答
  •  盖世英雄少女心
    2020-12-11 06:04

    You have two options. First (evil) if to use eval() function - i.e. interpret your string as code.

    Second is to parse your path. That will be:

    //$path = "['a']['b']['c']";
    preg_match_all("/\['(.*?)'\]/", $path, $rgMatches);
    $rgResult = $array;
    foreach($rgMatches[1] as $sPath)
    {
       $rgResult=$rgResult[$sPath];
    }
    

提交回复
热议问题