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)

3つの出力すべての単一の配列、つまり要素を持つ配列を作成するにはどうすればよいですか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: 正確に何をしようとしているのかはわかりませんが、参照渡ししない限り、最終的な配列を返す停止条件を追加する必要があるでしょう。

アップデート

これを行う1つの方法は次のとおりです。

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 に答える