0

I've been trying to unflatten an array with a recursive lambda function but I can't seem to get my head around it.

$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>";

That's the code but I have no idea what to do in the "// Missing logic here." part.

I'd like this recursive lambda function to convert

[0, 1, 2] 

Into:

Array
(
    [0] => Array
        (
            [1] => Array
                (
                    [2] => test
                )
        )
)
1
  • 2
    You'd have to explain what exactly that "// Missing logic here" should do. There's not an obvious route from [0, 1, 2] to [0 => [1 => [2 => 'test']]], when "test" is not specified anywhere. Commented Nov 29, 2017 at 21:04

1 Answer 1

1

You don't need the 2nd argument

$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

Sign up to request clarification or add additional context in comments.

4 Comments

I guess count and $c aren't needed either: return $a ? [array_shift($a) => $test($a)] : 'test';
Yes, you are right. But if OP's code is almost working, I usually save as much as possible.
That makes sense. I wasn't necessarily suggesting you should change your answer, though. Just commenting.
@Don'tPanic Well, that's right, especially if take into account that your code is very elegant :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.