我有这个数组:
$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操作。
答案 0 :(得分:2)
这是一种使用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);