use strings to access (potentially large) multidimensional arrays

前端 未结 4 721
生来不讨喜
生来不讨喜 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:19

    Considering $vars being your variables you would like to get one['one-one'] or two['two-two']['more'] from (Demo):

    $vars = function($str) use ($vars)
    {
        $c = function($v, $w) {return $w ? $v[$w] : $v;};
        return array_reduce(preg_split('~\[\'|\'\]~', $str), $c, $vars);
    };
    echo $vars("one['one-one']"); # hello
    echo $vars("two['two-two']['more']"); # tea-time!
    

    This is lexing the string into key tokens and then traverse the $vars array on the keyed values while the $vars array has been turned into a function.


    Older Stuff:

    Overload the array with a function that just eval's:

    $vars = array(
        'one' => array(
            'one-one' => "hello",
            'one-two' => "goodbye"
        ),
        'two' => array(
            'two-one' => "foo",
            'two-two' => "bar"
        )
    );
    
    $vars = function($str) use ($vars)
    {
        return eval('return $vars'.$str.';');
    };
    
    echo $vars("['one']['one-two']"); # goodbye
    

    If you're not a fan of eval, change the implementation:

    $vars = function($str) use ($vars)
    {
        $r = preg_match_all('~\[\'([a-z-]+)\']~', $str, $keys);
        $var = $vars;
        foreach($keys[1] as $key)
            $var = $var[$key];
        return $var;
    };
    echo $vars("['one']['one-two']"); # goodbye
    

提交回复
热议问题