PHP 该多维数组如何递归循环?

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

存在children数组则将children数组里的id赋值给新的数组,最终组成新的数组如下:

$arr2 = [
    [1,2,3,4],
    [5,6],
    [7]
];
动漫人物
浏览 408回答 2
2回答

料青山看我应如是

<?php $arr = [ [ 'id' => 1, 'children' => [ 'id' => 2, 'children' => [ 'id' => 3, 'children' => [ 'id' => 4 ] ] ] ], [ 'id' => 5, 'children' => [ 'id' => 6, ] ], [ 'id' => 7 ] ]; function pushChild($children, &$container) { $container[] = $children['id']; if (! isset($children['children'])) { return; } pushChild($children['children'], $container); } $arr2 = []; foreach ($arr as $item) { $result = []; pushChild($item, $result); $arr2[] = $result; } var_dump($arr2); 输出 ~ ❯❯❯ php test.php array(3) { [0]=> array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) } [1]=> array(2) { [0]=> int(5) [1]=> int(6) } [2]=> array(1) { [0]=> int(7) } }

鸿蒙传说

$data = new \RecursiveArrayIterator($data); $iterator = new \RecursiveIteratorIterator($data,\RecursiveIteratorIterator::SELF_FIRST); $iteratorArr = []; foreach ($iterator as $key=>$element) { } 试试RecursiveArrayIterator递归
打开App,查看更多内容
随时随地看视频慕课网APP