用递归lambda功能突破简单的阵列



我一直在试图用递归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
                )
        )
)

您不需要第二个参数

$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] );

demo

最新更新