-1

I have a recursive function. How can I return a value from this recursive function at the last call?

public function deneme($parent_id = 0, $sub_mark = 0, $str = '') {
    $this->db->select('*');
    $this->db->from('categories');
    $this->db->where('parent_id = ' . $parent_id);
    $this->db->order_by('id', 'ASC');
    $query = $this->db->get();
    if($query->num_rows() > 0) {
        $str .= '<ul>';
        foreach($query->result_array() as $row) {
            if ($parent_id == 0) {
                $str .= '<li class="active">';
            } else {
                $str .= '<li>';
            }
            $str .= '<a href="index.html">' . $row['name'] . '</a> </li> '; 
            $sub_mark++;
            $this->deneme($row['id'], $sub_mark, $str);
        }
        $str .= '</ul>';
    }
}

I want to return the str variable.

1 Answers1

2

Looks as though you need a couple of changes, first to return the built up string from the routine at the end...

        }
        $str .= '</ul>';
    }
    return $str;
}

The second is where you call the routine recursively, you need to set the the return value to the string you are generating...

$str = $this->deneme($row['id'], $sub_mark, $str);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55