To create the N-level Categories tree with single SQL query using CI
class Category_model extends Model {
private $table = 'categories';
private $selectTreeOptions_data = null;
private $selectTreeOptions_index = null;
public function get_categories() {
$this->db->select('c.id, c.parent_id, c.name');
$this->db->from($this->table .' AS c');
$this->db->where('c.status', '1');
$query = $this->db->get();
//$str = $this->db->last_query();
return $query->result_array();
}
/*
* Recursive top-down tree traversal example:
* Indent and print child nodes
*/
function getSelectTreeOptions($parent_id, $level, $selected_id='')
{
$html = '';
$data = $this->selectTreeOptions_data;
$index = $this->selectTreeOptions_index;
$parent_id = $parent_id === NULL ? 0 : $parent_id;
if (isset($index[$parent_id])) {
foreach ($index[$parent_id] as $id) {
$selected = isset($selected_id) && ($selected_id==$data[$id]["id"]) ? 'selected="selected"' : '';
$html .= '\n";
$html .= $this->getSelectTreeOptions($id, $level + 1, $selected_id);
}
}
return $html;
}
// Get the category tree with select options.
function get_categories_tree_options($selected_id='')
{
$categories = $this->get_categories();
$this->data = '';
$this->index = '';
foreach ($categories as $row) :
$id = $row["id"];
$parent_id = $row["parent_id"] === NULL ? "NULL" : $row["parent_id"];
$this->selectTreeOptions_data[$id] = $row;
$this->selectTreeOptions_index[$parent_id][] = $id;
endforeach;
$items = $this->getSelectTreeOptions(NULL, 0, $selected_id);
return $items;
}
}
Category_model::get_categories_tree_options($selected_id='');
No comments:
Post a Comment
Please post any queries and comments here.