1

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?

1 Answer 1

4

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');
print_r($a);

Output:

Array
(
    [1] => Array
        (
            [1] => Array
                (
                    [1] => hello
                )

        )

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

Comments

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.