问题
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