PHP 将字符串键数组转换为多键数组

PHP convert string key array to multi key array

我有这个数组:

$array['a.b.c'] = 'x';
$array['a.b.d'] = 'y';
$array['e.f'] = 'z';

要转换成这个数组的内容:

$array['a']['b']['c'] = 'x';
$array['a']['b']['d'] = 'y';
$array['e']['f'] = 'z';

在PHP有什么快速方法吗?

谢谢 O.

下面是一种使用 foreach 的方法,它遍历数组的每个键,分解它,并将分解后的值用作新数组的键:

$result = array();

foreach($array as $key => $value) {
    $new_keys = explode('.',$key);
    $last_key = array_pop($new_keys); //remove last key from $new_keys 
    $a =& $result; //make $a and $result be the same variable

    foreach($new_keys as $new_key) {
        if(!isset($a[$new_key])) {
            $a[$new_key] = array();
        }

        $a =& $a[$new_key]; //reset $a to $a[$new_key]
    }

    $a[$last_key] = $value; //put $value in the last key
}

print_r($result);