dongtuanzi1080 2013-09-26 12:57
浏览 27
已采纳

使用动态路径访问阵列

I have an issue in accessing the array in php.

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

In the above piece of code I have an multidimensional array named $array.

$path is a dynamic value which I would get from database.

Now I want to retrieve the value from $array using $path but I am not able to.

$value = $array.$path

returns me

Array['a']['b']['c']

rather than the value.

I hope I have explained my question properly.

  • 写回答

3条回答 默认 最新

  • dreamice2013 2013-09-26 13:03
    关注

    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];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?