这是一种使用递归函数的方法。这是我个人最喜欢的,因为它具有很好的可读性。
function nest(array $keys, $value) {
if (count($keys) === 0)
return $value;
else
return [$keys[0] => nest(array_slice($keys, 1), $value)];
}
$result = nest(['key1', 'key2', 'key3'], 'foo');
print_r($result);
// Array
// (
// [key1] => Array
// (
// [key2] => Array
// (
// [key3] => foo
// )
// )
// )
或者您可以使用array_reduce 的另一种方法。这种方式也很不错,但是这里增加了一点复杂性,因为必须先反转键数组。
function nest(array $keys, $value) {
return array_reduce(array_reverse($keys), function($acc, $key) {
return [$key => $acc];
}, $value);
}
$result = nest(['key1', 'key2', 'key3'], 'foo');
print_r($result);
// Array
// (
// [key1] => Array
// (
// [key2] => Array
// (
// [key3] => foo
// )
// )
// )
这两种解决方案都适用于任意数量的键。即使$keys 是一个空数组
nest([], 'foo'); //=> 'foo'