Search code examples
phparrayscodeigniterrecursionarray-push

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


I am trying to solve this branch tree searching, I want to collect all value of the branch in 1 variable array, and the problem is, branch function returning only 2 value when there is a lot of value, actually I am using Codeigniter.

This is my parent function :

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

and this is my branch function :

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

Solution

  • The main reason is local declaration of $br in branch function. This should work

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