use strings to access (potentially large) multidimensional arrays

前端 未结 4 706
生来不讨喜
生来不讨喜 2020-11-29 11:39

I am having trouble figuring out a way to simply parse a string input and find the correct location within a multidimensional array.

I am hoping for one or two lines

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 12:39

    For one, you've not got a $var in your get() function. $var was defined outside the function, and PHP scoping rules do not make "higher" vars visible in lower scopes unless explictly made global in the lower scope:

    function get($string) {
       global $vars;
       eval('$x = $vars' . $string);
       return $x;
    }
    
    get("['two']['two-two']");
    

    might work, but this isn't tested, and using eval is almost always a very bad idea.

提交回复
热议问题