1

如何从 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 

当我在模型中执行此操作时,一切正常,但是当我尝试调用控制器并在视图中循环时,我得到的结果类似于上面的示例:

这项工作在模型中:

   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 

任何人都有解决方案或示例,谢谢。

4

1 回答 1

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>
于 2013-08-07T05:31:40.307 回答