如何在Codeigniter中从db获取分层数据。我看了这个: http://www.sitepoint.com/hierarchical-data-database/ 我做得很好,但我不能用我的模型,控制器和视图来优化本教程
Default Category
|----- Sub category
| ----One more category
|----- Somthing else
我尝试但不显示子类别:
我的模特:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$this->data[$row->id] = $row;
//echo str_repeat(' ',$level).$row['title']."\n";
}
return $this->data;
}
控制器:
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
查看:
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th> <?php echo str_repeat('|----', 0+1). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
输出是:
----Default
----Default
----Test Category 1
----Seccond Test Category 1
----Another Test Category 1
当我在模型中执行此操作时,所有工作正常但当我尝试在控制器中调用并在视图中循环时,我的结果如上所示:
这项工作onlu in model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
echo str_repeat('|-----',$level).$row->title."\n";
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
就像输出一样:
Default
|----Test Category 1
|----Seccond Test Category 1
|----Another Test Category 1
任何人都有解决方案或示例谢谢。
答案 0 :(得分:0)
尝试存储每个类别的级别值。
在你的模特中:
public function fetchChildren($parent, $level){
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$row->level = $level;
$this->data[] = $row;
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
在您的控制器中:
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
在你看来
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th><?php echo str_repeat('|----', $row->level). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>