PHP:递归修改数组?

时间:2010-06-08 16:34:03

标签: php arrays multidimensional-array

我试图创建一个迭代通过以下数组的函数来展平它并在适用的情况下向父级添加父ID。我只是无法使它工作,所以我希望这里的任何人都知道该怎么做:

这是起点:

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

预期结果:

Array (

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

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

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

)

希望有人能指出我正确的方向。非常感谢!

解决方案(感谢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;
        }

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

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

1 个答案:

答案 0 :(得分:4)

这次我测试了它。这确实有效!

$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);

它返回:

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

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

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

)