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

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

问题描述

我需要将 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 变成$test[1][1][1] 然后我可以存储相应的 Name 作为值.

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天全站免登陆