Nested numbering to array keys

I need to convert following data in csv to nested tree

S.No    Name
1       A
1.1     B
1.1.1   C
1.1.2   D
2       E
2.1     F
2.2     G

Is there any way S.No can be used to make array keys like 1.1.1 to $test[1][1][1] and then I can store corresponding Name as value.

or I should make parent child type array?
What would be the best approach to convert this to tree/nested list?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can use this function to set a nested value within an array:

function set_nested_value(array &$array, $index, $value)
    $node = &$array;

    foreach (explode('.', $index) as $path) {
        $node = &$node[$path];

    $node = $value;

$a = array();
set_nested_value($a, '1.1.1', 'A');


    [1] => Array
            [1] => Array
                    [1] => hello



Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply