从代码点火器中的递归函数创建一个数组


Creating an array from recursive function in codeigniter

我想在Codeigniter中使用递归创建一个数组。 我在控制器中的函数make_tree()是:

function make_tree($customer_id,$arr = array()){
    $ctree = $this->customer_operations->view_customer_tree($customer_id);
    foreach($ctree as $v):
        echo $customer_id = $v['customer_id'];
        array_push($arr, $customer_id);
        $this->make_tree($customer_id);
    endforeach;
    var_dump($arr);
}

var_dump($arr)echo结果输出如下:

1013
array
  empty
array
  0 => string '13' (length=2)
11
array
  empty
array
  0 => string '10' (length=2)
  1 => string '11' (length=2)

如何制作所有三个输出的单个数组,即具有元素的数组13,10,11

您需要

发送带有参数的数组,否则将创建一个新数组。

function make_tree($customer_id,$arr = array()){
    $ctree = $this->customer_operations->view_customer_tree($customer_id);
    foreach($ctree as $v):
        echo $customer_id = $v['customer_id'];
        array_push($arr, $customer_id);
        $this->make_tree($customer_id, $arr);
    endforeach;
    var_dump($arr);
}

PS:我不知道你到底想做什么,但你可能需要添加一个将返回最终数组的停止条件,除非你想通过引用传递它。

更新

这是一种方法:

function make_tree($customer_id, &$arr)
{
    $ctree = $this->customer_operations->view_customer_tree($customer_id);
    foreach($ctree as $v):
        $customer_id = $v['customer_id'];
        array_push($arr, $customer_id);
        $this->make_tree($customer_id, $arr);
    endforeach;
}

这就是你使用它的方式:

$final_array = array();
make_tree($some_customer_id, $final_array);
// now the $final_array is populated with the tree data

您可以使用类作用域。

class TheController {
private $arr = array();
function make_tree($customer_id){
    $ctree = $this->customer_operations->view_customer_tree($customer_id);
    foreach($ctree as $v) {
        $customer_id = $v['customer_id'];
        array_push($this->arr, $customer_id);
        $this->make_tree($customer_id);
    }
}
}