duangan6133 2018-08-17 03:56
浏览 45

将多维数组转换为简单数组

I have an array like this

Array 
( 
    [0] => Array 
    ( 
        [id] => 1 [children] => Array 
        ( 
            [0] => Array 
            ( 
                [id] => 2 [children] => Array 
                ( 
                    [0] => Array 
                    ( 
                        [id] => 3 [children] => Array 
                        ( 
                            [0] => Array 
                            ( 
                                [id] => 4 
                            ) 
                        ) 
                    ) 
                ) 
            ) 
        ) 
    ) 
    [1] => Array ( 
        [id] => 5 
    ) 
    [2] => Array 
    ( 
        [id] => 6 
    ) 
    [3] => Array 
    ( 
        [id] => 7 
    ) 
    [4] => Array 
    ( 
        [id] => 8 
    ) 
    [5] => Array 
    ( 
        [id] => 9 
    ) 
)

this is dynamically generated array i need a function that takes this array as input and returns each id with its parent id

as according to this array id 2 is child of id 1 and id 3 is child of id 3 and id 4 is child of id 3

and final result id 1 is parent of id 2 and id 2 is parent of id 3 and id 3 is parent of id 4 and ids 5-9 have no parents so they have 0 as default value

  • 写回答

1条回答 默认 最新

  • dongtou2097 2018-08-17 06:48
    关注

    Beside the fact that you didn't come up with any effort by yourself, i'll post a solution anyway in case someone isn't aware of a solution with PHP's RecursiveIteratorIterator

    Sample Data:

    $arrData = [
        [
            'id' => 1,
            'children' => [
                'id' => 2,
                'children' => [
                    'id' => 3,
                    'children' => [
                        'id' => 4
                    ]
                ]
            ]
        ],
        [
            'id' => 5
        ],
        [
            'id' => 6
        ],
        [
            'id' => 7
        ],
        [
            'id' => 8
        ],
        [
            'id' => 9
        ],
    ];
    

    Use of PHP's built int iterator classes

    $arrDataConverted = [];
    
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arrData));
    foreach($iterator AS $key => $value)
    {
        $arrParentdata = $iterator->getSubIterator($iterator->getDepth()-1);
    
        $arrItem = [
            'id' => $value,
            'parent' => (isset($arrParentdata['id']))  ?    $arrParentdata['id']   :   0
        ];
        $arrDataConverted[] = $arrItem;
    }
    
    print_r($arrDataConverted);
    
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法