如何在递归函数上使用数组推送添加数组值 php

how to add an array value using array push on reqursive function php

我正在尝试解决这个分支树搜索问题,我想在 1 个变量数组中收集分支的所有值,问题是,分支函数 只返回 2 个值当有很多价值时,实际上我正在使用Codeigniter。

这是我的父函数:

$data['left'] = array();
    $data['right'] = array();
    $c=array();
    foreach ($root as $r){
        if ($r->branch_status=="L"){
            array_push($data['left'], array($r->member_id, $r->member_name, $r->member_phone));
            $c = $this->branch($r->member_id);
            for ($i=0; $i<count($c); $i++){
              echo "array member : ".$c[$i][0]."<br>";
            }
        } else if ($r->branch_status="R"){
            array_push($data['right'], array($r->member_id, $r->member_name, $r->member_phone));
            $c = $this->branch($r->member_id);
            for ($i=0; $i<count($c); $i++){
              echo "array member : ".$c[$i][0]."<br>";
            }
        }
    }

这是我的分支函数:

public function branch($id){
    $br = array();
    $branch = $this->M_member->member($id);
    foreach ($branch as $b){
        if (empty($b)){
           echo "empty member";
        } else{
            array_push($br,array($b->member_id,$b->member_phone));
            $this->branch($b->member_id);
        }
    }
    for ($i=0; $i<count($br); $i++){
        echo "array member : ".$br[$i][0]." phone : ".$br[$i][1]."<br>";
    }
   return $br;
}

主要原因是在分支函数中局部声明了$br。这应该有效

public function branch($id, &$br=array()){

    $branch = $this->M_member->member($id);

    foreach ($branch as $b){
        if (empty($b)){
            echo "empty member";
        } else{
            //array_push($br,array($b->member_id,$b->member_phone));
            $br[] = array($b->member_id,$b->member_phone);
            $this->branch($b->member_id, $br);
        }
    }
    return $br;
}