use strings to access (potentially large) multidimensional arrays

前端 未结 4 710
生来不讨喜
生来不讨喜 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: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 );
    

提交回复
热议问题