0

我想在 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

4

2 回答 2

1

您需要发送带有参数的数组,否则会创建一个新数组。

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
于 2013-10-09T05:11:05.153 回答
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);
    }

}

}
于 2013-10-09T08:16:09.707 回答