使用子项从平面数组创建嵌套数组

时间:2013-02-19 14:40:58

标签: php json multidimensional-array nested

我对嵌套数组有疑问;我在google和stackoverflow上搜索但找不到符合我需要的解决方案: - /

我有以下数组:

Array
(
    [0] => Array
        (
            [name] => Europe
            [children] => Array
                (
                    [0] => West
                    [1] => East
                    [2] => South
                    [3] => North
                    [4] => Zimbabwe
                )
        )
    [1] => Array
        (
            [name] => West
            [children] => Array
                (
                    [0] => Germany
                    [1] => France
                    [2] => Switzerland
                    [3] => Netherlands
                    [4] => Belgium
                    [5] => Luxembourg
                    [6] => United Kingdom
                    [7] => Ireland
                )
        )
    [2] => Array
        (
            [name] => Germany
            [children] => 
        )
    [3] => Array
        (
            [name] => France
            [children] => 
        )
)

我想将其转换为嵌套,意思是:

Array
(
    [0] => Array
        (
            [name] => Europe
            [children] => Array
                (
                    [0] => Array
            (
               [name] => West
               [children] => Array
                (
                  [0]=> Array
                  (
                    [name] => Germany
                  )
                  [1]=> Array
                  (
                    [name] => France
                  )
                )
            )
                    [2] => Array
            (
               [name] => East
               [children] => Array
                (
                  [0]=> Array
                  (
                    [name] => Poland
                  )
                  [1]=> Array
                  (
                    [name] => Austria
                  )
                )
            )
        )
        )
)

你有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

foreach ($unnested_ary as $one_k => $one_v)
{
    foreach ($one_v as $two_k => $two_v)
    {
        if ($two_k == 'children')
        {
            foreach ($two_v as $three_k => $three_v)
            {
                $unnested_array[$one_k][$two_k][$three_k][] = array(array(
                    'name' => $three_v
                ));
            }
        }
    }
}

我不确定我是否正确嵌套它,但你应该明白并使用这段代码。这基本上应该像你问的那样创建新的键和值。