嵌套编号到数组键 [英] Nested numbering to array keys

查看:146
本文介绍了嵌套编号到数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以下数据以CSV转换为嵌套树

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

有什么办法 S.No 可用于制造数组键 1.1.1 $测试[1] [1] [1] 然后我可以存储相应的名称的值。

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?

推荐答案

您可以使用此功能在阵列内设置一个嵌套的值:

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);

输出:

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

        )

)

这篇关于嵌套编号到数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆