There is a recursion in Codeigniter

function get_tree($pid) { $this->db->select('id, name, parent_id'); $this->db->where('parent_id',$pid); $tree = $this->db->get("catalog")->result_array(); $count = $this->db->count_all_results(); $html = ''; foreach ($tree as $row) { if ($row['parent_id'] == $pid) { $html .= '<li>' . "\n"; $html .= ' ' . $row['name'] . "\n"; $html .= ' ' . $this->get_tree($row['id']); $html .= '</li>' . "\n"; } } return $html ? '<ul>' . $html . '</ul>' . "\n" : ''; } 

So, I call this:

 echo "<ul class='menu'>"; echo $this->leftmenu->get_tree('0'); echo "</ul>"; 

And so the thing is, recursion starts and writes a new <*ul> tag at the beginning, as a result of which my class menu does not fall into the list. How to be?
That is, it turns out like this:

 <ul class='menu'> <ul> <li>test</li> <li>test <ul><li>test_2</li> <li>test_2</li> </ul></li> <li>test</li> </ul> </ul> 
  • Understood. - dogmar

1 answer 1

Rewrite this line:

  return $html ? '<ul>' . $html . '</ul>' . "\n" : ''; 

on

  return $html ? '<ul class="menu">' . $html . '</ul>' . "\n" : ''; 

Better yet, rewrite it to:

  return $html; 

Then your code will work as you planned, and, of course, you will be able to write the classes that you need. Well, or, rewrite the function something like this:

 function get_tree($pid, $className = null) { $this->db->select('id, name, parent_id'); $this->db->where('parent_id',$pid); $tree = $this->db->get("catalog")->result_array(); $count = $this->db->count_all_results(); $html = ''; foreach ($tree as $row) { if ($row['parent_id'] == $pid) { $html .= '<li>' . "\n"; $html .= ' ' . $row['name'] . "\n"; $html .= ' ' . $this->get_tree($row['id']); $html .= '</li>' . "\n"; } } $ulStart = ($className != null) ? '<ul class="'.$className.'">' : '<ul>'; return $html ? $ulStart . $html . '</ul>' . "\n" : ''; } // если переписать так, то вызывается функция так: // get_tree($pId, $className); // ------ где className значения атрибута `class` // ------ корневого ul эдемента 
  • I did so if ($ pid> 0) {$ ul = "<ul>"; $ closeul = "</ ul>"; } else {$ ul = ""; $ closeul = ""; } and return the return $ html? $ ul. $ html. $ closeul. "\ n": ''; - dogmar