Skip to content
Advertisement

How to create recursive array from the loop PHP? [closed]

I have an array like below and its dynamic array.

$array = [10,20,30,40,50];

I want to create an another array recursively using the above array values. Looks like below

Array
(
    [10] => Array
        (
            [20] => Array
                (
                    [30] => Array
                        (
                            [40] => Array
                                (
                                    [50] => Array
                                        (
                                            [label] => LABEL
                                        )

                                )

                        )

                )

        )

)

Can anyone help / assist for the above query?

Your help very much appreciated.

Thanks in advance.

Advertisement

Answer

It’s just a loop, not recursive. If it was recursive you’d need 2 functions or call the same function from within itself. This looks a bit like that, but it’s just a loop.

Iterate through each number and create a new array using the number as the key and the accumulating array as the value. Doing it this way means that the first item in the original array will be the deepest item in the finished array, so array_reverse is needed to get it the way you described.

$array = [10,20,30,40,50];
$newarray=[];
foreach (array_reverse($array) as $number) $newarray = [$number => $newarray];
print_r($newarray);

https://www.tehplayground.com/bya12n5tV0jjcAvA

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement