首頁 >後端開發 >php教程 >PHP如何递归保存到一个数组里面

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

WBOY
WBOY原創
2016-06-06 20:23:291351瀏覽

源数据如下。

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

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

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

回复内容:

源数据如下。

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

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

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

<code><?php $arr = Array
            (
                'id' => 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);</code>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn