How to create recursive array from the loop PHP?

53 Views Asked by At

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.

2

There are 2 best solutions below

2
Kinglish On BEST 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

0
Liakos On
<?php
$array = [10, 20, 30, 40, 50];
$matrix = []; // Final result.

$pointer = &$matrix; // Reference of deepest array.
foreach ($array as $item) {
    $pointer[$item] = []; // Create a deeper array.
    $pointer = &$pointer[$item]; // Move the reference to the deeper array.
}
$pointer['label'] = "LABEL";

// Print result.
print(json_encode($matrix, JSON_PRETTY_PRINT));

Output

{
    "10": {
        "20": {
            "30": {
                "40": {
                    "50": {
                        "label": "LABEL"
                    }
                }
            }
        }
    }
}