使用递归函数时在哪里传递临时数组?

时间:2015-11-15 21:55:49

标签: php recursion

我在递归函数中使用foreach循环。但我无法弄清楚在哪里通过我的退货声明。我需要在某个时候返回我的临时数组,但我不知道该怎么做:

<?php
    $patterns = function($array, $temp = array(), $i = 0, $id = 0, $parent = 0) use(&$patterns) {
        $return = null;

        if(array_key_exists($i, $array)) {
            foreach($array[$i] as $set) {
                if($parent == $set['id']) {
                    $data = array(
                        'id' => $set['id'],
                        'parent' => $set['parent']
                    );

                    array_push($temp, $data);
                }

                $patterns($array, $temp, $i + 1, $set['id'], $set['parent']);
            }
        }
    };

    print_r($patterns($rev_relations));
?>

这是我的数据:

Array(
    [0] => Array(
            [0] => Array(
                    [id] => 60
                    [parent] => 55
                )
            [1] => Array(
                    [id] => 57
                    [parent] => 54
                )
        )
    [1] => Array(
            [0] => Array(
                    [id] => 61
                    [parent] => 50
                )
            [1] => Array(
                    [id] => 54
                    [parent] => 49
                )
        )
    [2] => Array(
            [0] => Array(
                    [id] => 49
                    [parent] => 0
                )
        )
)

1 个答案:

答案 0 :(得分:1)

<?php


//pass $temp by reference so outside variable gets populated
    $patterns = function($array, &$temp, $i = 0, $id = 0, $parent = 0) use(&$patterns) {
        $return = null;

        if(array_key_exists($i, $array)) {
            foreach($array[$i] as $set) {
                if($parent == $set['id']) {
                    $data = array(
                        'id' => $set['id'],
                        'parent' => $set['parent']
                    );

                    array_push($temp, $data);
                }

                $patterns($array, $temp, $i + 1, $set['id'], $set['parent']);
            }
        }
    };

    //actuall array is created on temp  here
    $temp=array();
    $patterns($rev_relations,$temp);
?>

这不行吗?从来没有真正使用无名函数,但这就是我将如何在一个正常的递归函数上进行它

好的,拿两个

<?php

    $patterns = function($array, $temp = array(), $i = 0, $id = 0, $parent = 0) use(&$patterns) {
        $return = null;

        if(array_key_exists($i, $array)) {
            foreach($array[$i] as $set) {


          if($parent == $set['id']) {
                $data = array(
                    'id' => $set['id'],
                    'parent' => $set['parent']
                );

                array_push($temp, $data);
            }

            return $patterns($array, $temp, $i + 1, $set['id'], $set['parent']);
        }
    }
    else
    {
       return $temp;
    }
};


$patterns($rev_relations);
?>