我一直试图用一个递归的lambda函数来解除数组,但我似乎无法理解它。
$test = function( $a, $b ) use ( &$test ) {
if ( ! count($a) ) return $b;
$b[array_shift($a)] = []; // Missing logic here.
return $test( $a, $b );
};
$newArr = $test( [0, 1, 2], [] );
echo "<pre>";
print_r($newArr);
echo "</pre>";
这是代码,但我不知道该怎么做“//这里缺少逻辑”。一部分。
我想要这个递归的lambda函数来转换
[0, 1, 2]
分为:
Array
(
[0] => Array
(
[1] => Array
(
[2] => test
)
)
)
答案 0 :(得分:1)
你不需要第二个参数
$test = function( $a) use ( &$test ) {
// the leaf element
if ( ! count($a) ) return 'test';
$c = array_shift($a);
return [$c => $test($a)];
};
$newArr = $test( [0, 1, 2] );