dpvr49226 2013-10-09 05:05
浏览 49

从codeigniter中的递归函数创建数组

I want to create an array using recursion in Codeigniter. my function make_tree() in controller is :

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

}

But the var_dump($arr) and echo results output like:

1013

array
  empty

array
  0 => string '13' (length=2)

11

array
  empty

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

How can I make a single array of all the three outputs, ie an array with elements 13,10,11

  • 写回答

2条回答 默认 最新

  • doujilou3903 2013-10-09 05:11
    关注

    you need to send the array with the parameters otherwise a new array is created.

    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: I don't know what you are trying to do exactly, but you probably need to add a stopping condition that is going to return the final array, unless you want to pass it by reference.

    UPDATE

    Here is one way to do it:

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

    and this is how you'd use it:

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

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码