0

我有一个关于嵌套数组的问题;我在 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
                  )
                )
            )
        )
        )
)

你有想法吗 ?

提前致谢!

4

1 回答 1

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

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

于 2013-02-19T15:14:22.330 回答