0

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.

raheem.unr
  • 797
  • 1
  • 7
  • 16

2 Answers2

2

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

Kinglish
  • 23,358
  • 3
  • 22
  • 43
0
<?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"
                    }
                }
            }
        }
    }
}
Liakos
  • 512
  • 5
  • 10