Home > Backend Development > PHP Tutorial > PHP如何递归保存到一个数组里面

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

WBOY
Release: 2016-06-06 20:23:29
Original
1354 people have browsed it

源数据如下。

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

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

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

回复内容:

源数据如下。

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

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

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

<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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template