php - 在codeigniter中,从递归函数创建一个 array

  显示原文与译文双语对照的内容
0 0

我想在Codeigniter中使用递归创建一个 array 。 我的控制器中的函数 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)

如何制作所有三个输出的单个 array,IE 一个带有元素 13,10,11的array

时间: 原作者:

0 0

你需要使用参数发送 array,否则会创建一个新的array 。


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

}

我不知道你正在做什么,但是你可以能需要添加一个停止条件来返回最终 array 。

更新

下面是一个实现这里目的的方法:


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

0 0

你可以使用类范围。


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

}

}

原作者:
...