解析字符串以获取数组元素[重复]

This question already has an answer here:

I'm trying to figure out how to take a string, parse it, and get the corresponding array values that match the parsed keys back. I don't know how to properly explain this, so here's an example.

$testArray = array(
    'router' => array(
        'format' => 'xml',
    ),
);

The string I want to parse will look like this - router.format, and I'm obviously expecting back xml as a string. The passed in string can have any arbitrary amount of separating periods. I was thinking of doing recursion somehow, but I can't think of any way in which this will work.

This is very similar to SF2's service container and the way in which you get services back.

Any help would be great!

</div>

Might need some error checking:

$testArray = array(
    'router' => array(
        'format' => 'xml',
    ),
);
$path = 'router.format';

$result = $testArray;
foreach(explode('.', $path) as $key) {
    if(isset($result[$key])) {
        $result = $result[$key];
    }
}
print_r($result);
<?php
    $string = 'router.format';
    $array = array(
        'router' => array(
            'format' => 'xml',
        ),
    );

    $string = explode('.', $string);
    $result = $array;

    for($i = 0; $i < count($string); ++$i)
    {  
        $key = $string[$i];
        if(isset($result[$key]))
            $result = $result[$key];
        else
            break;
    }

    print_r($result);

Laravel has a helper function which does this: http://laravel.com/api/source-function-array_get.html#226-251

The code for the function is:

function array_get($array, $key, $default = null)
{
    if (is_null($key)) return $array; 
    if (isset($array[$key])) return $array[$key];
    foreach (explode('.', $key) as $segment)
    {
         if ( ! is_array($array) or ! array_key_exists($segment, $array))
         {
             return value($default);
         }

         $array = $array[$segment];
    }

    return $array;
}

function value($value)
{
     return $value instanceof Closure ? $value() : $value;
}

Usage:

array_get($testArray, 'router.format');

Recursive method.

function array_path($keys, $array) {
    $key = array_shift($keys);
    if (!isset($array[$key])) { return false; }
    return !empty($keys) ? array_path($keys, $array[$key]) : $array[$key];
}

$testArray = array(
    'router' => array(
        'format' => 'xml',
    ),
);
$keys = explode('.', 'router.format');

var_dump(array_path($keys, $testArray));