use strings to access (potentially large) multidimensional arrays

前端 未结 4 707
生来不讨喜
生来不讨喜 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
    
    0 讨论(0)
  • 2020-11-29 12:21

    Kohana has a nice Config class which alows something like this:

    echo Config::get("two.two-two");
    

    You can check it out here: http://kohanaframework.org/3.1/guide/api/Config

    0 讨论(0)
  • 2020-11-29 12:34

    How about

    $vars = array(
        'one' => array(
            'one-one' => "hello",
            'one-two' => "goodbye"
        ),
        'two' => array(
            'two-one' => "foo",
            'two-two' => "bar"
        )
    );
    
    function get( $string, $vars )
    {
        $keys = explode( '][', substr( $string, 1, -1 ) );
        foreach( $keys as $key ) {
            $vars = $vars[$key];
        }
        return $vars;
    }
    
    echo get( '[two][two-one]', $vars );
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题