Nested numbering to array keys

此生再无相见时 提交于 2019-12-17 16:53:42

问题


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:


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
                )

        )

)


来源:https://stackoverflow.com/questions/20259773/nested-numbering-to-array-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!