当前位置:Gxlcms > PHP教程 > PHP如何递归保存到一个数组里面

PHP如何递归保存到一个数组里面

时间:2021-07-01 10:21:17 帮助过:67人阅读

源数据如下。

Array
(
    [id] => 1
    [level] => CEO
    [children] => Array
        (
            [id] => 2
            [level] => CTO
            [children] => Array
                (
                    [id] => 3
                    [level] => CFO
                )
        )
)

如何递归成如下格式呢?多谢各位。

Array
(
    [0] => Array
        (
            [id] => 1
            [level] => CEO
        )
    [1] => Array
        (
            [id] => 2
            [level] => CTO
        )
    [2] => Array
        (
            [id] => 3
            [level] => CFO
        )
)

回复内容:

源数据如下。

Array
(
    [id] => 1
    [level] => CEO
    [children] => Array
        (
            [id] => 2
            [level] => CTO
            [children] => Array
                (
                    [id] => 3
                    [level] => CFO
                )
        )
)

如何递归成如下格式呢?多谢各位。

Array
(
    [0] => Array
        (
            [id] => 1
            [level] => CEO
        )
    [1] => Array
        (
            [id] => 2
            [level] => CTO
        )
    [2] => Array
        (
            [id] => 3
            [level] => CFO
        )
)

 1,
                'level' => 'CEO',
                'children' => Array
                    (
                        'id' => 2,
                        'level' => 'CTO',
                        'children' => Array
                            (
                                'id' => 3,
                                'level' => 'CFO'
                            )
                    )
            );
    
    $new_arr = array();
    $i = 0;
    function recur($arr,&$new_arr,$i){
        $new_arr[$i]['id'] = $arr['id'];
        $new_arr[$i]['level'] = $arr['level'];
        
        if(isset($arr['children'])){
            $i++;
            $arr = $arr['children'];
            recur($arr,$new_arr,$i);
        }
    }
    
    recur($arr,$new_arr,$i);
    
    print_r($new_arr);

人气教程排行