开发者

PHP: Modifying array recursively?

开发者 https://www.devze.com 2023-01-03 05:25 出处:网络
I have tried to make a function that iterates through the following array to flatten it and add parent id to children, where applicable. I just can\'t make it work, so I hope that anyone here has an i

I have tried to make a function that iterates through the following array to flatten it and add parent id to children, where applicable. I just can't make it work, so I hope that anyone here has an idea of what to do:

Here's the starting point:

Array
(
    [0] => Array (
            [id] => 1
            [children] => array (
                [id] => 2
                [children] => Array (
                    [0] => Array (
                            [id] => 3
                    )
             )
        )
)

The expected result :

Array (

    [0] => array ( 
        [id] => 1
    )

    [1] => array ( 
        [id] => 2
    )

    [2] => array ( 
        [id] => 3,
        [parent] => 2
    ) 

)

Hope that anyone can point me in the right direction. Thanks a lot!

Solution (Thanks to Oli!):

$output = array();

        function dejigg($in) {
            global $output;

            if (!isset($in['children'])) {
                $in['children'] = array();
            }
            $kids = $in['children'] or array();
            unset($in['children']);
            if (!isset($in['parent'])) {
                $in['parent'] = 0; // Not neccessary but makes the top node's parent 0.
            }
            $output[] = $in;

            foreach ($kids as $child) {
                $child['parent'] = $in['id'];
                dejigg($child); // recurse
            }

            return $output;
   开发者_StackOverflow中文版     }

        foreach ($array as $parent) {
            $output[] = dejigg($parent);
        }

        $array = $output;
        print("<pre>".print_r($array,true)."</pre>");


I've tested it this time. This does work!

$input = array( array('id' => 1, 'children'=>array( array('id'=>2, 'children'=>array( array('id'=>3) ) ) ) )  );
$output = [];

function dejigg($in) {
    global $output;

    $kids = $in['children'] or array();
    unset($in['children']);
    $output[] = $in;

    foreach ($kids as $child) {
        $child['parent'] = $in['id'];
        dejigg($child); // recurse
    }
}

foreach ($input as $parent)
    dejigg($parent);

print_r($output);

And it returns:

Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 2
            [parent] => 1
        )

    [2] => Array
        (
            [id] => 3
            [parent] => 2
        )

)
0

精彩评论

暂无评论...
验证码 换一张
取 消