2013-08-06 183 views
3

你好,我有一个愚蠢的问题。但也许不是。 在数据库中,我有表类别和我有4色 Id,parent_id,标题和说明。 Parent_id是当前类别的子项。从数据库获取分层数据

Id | parent_id | title | description 

___________________________________________________ 

1 |  1  | Main Category | description 


2 |  1  | Sub Category | description 


3 |  2  | Other Category | description 

4 |  1  | Some Category | description 

好吧,我知道如何输入数据和显示结果;那不是问题。当我告诉结果表

<table> 
    <tr> 
     <td> Id </td> 
     <td> Parent </td> 
     <td> Title </td> 
     <td> Desc </td> 
    </tr> 
    <?php foreach($categories as $category): ?> 
    <tr> 
     <td> <?php echo $category->id; ?> </td> 
     <td> <?php echo $category->parent_id; ?> </td> 
     <td> <?php echo $category->title; ?> </td> 
     <td> <?php echo $category->eescription; ?> </td> 
    </tr> 
    <?php endforeach;?> 
</table> 

这下父母另一方类别下的伟大工程,展示孩子类别:表看起来是这样的:

1 |  1  | Main Category | description 
2 |  1  | Sub Category | description 
3 |  2  | Other Category | description  
4 |  1  | Some Category | description 

我的问题是如何列出所有类别和子类别这样

|-- Main Category 
     |--- Sub Category 
      |--- One more cat 

    |--Other Category 
     |--- Some Category 

像这样 enter image description here

可以使用forach()获取这些数据吗?任何示例如何做到这一点。

感谢

回答

2

阅读关于这个http://www.sitepoint.com/hierarchical-data-database-2/。应该解决你的问题。

+0

好,谢谢。我会检查 – Jony

+0

告诉我一个,我理解网站的教程。但是我很困惑,他说根类是空的。我需要为这个col设置哪种数据库col类型?我的类型是INT,何时是emty默认值是0.在教程中他说必须是空的。 – Jony

+0

父级字段在顶部必须为空。通常没有人使用顶级类别。它是一种抽象父类,从那里开始创建目录/类别导航。 – Eugene

1

我这样做。我正在研究Codeigniter框架。如果有需要的话,我会发布如何修复这个像截图一样。

只是简单的品牌型号:

型号

/* 
    * Get all children categories 
    * 
    * Get Hierarchical Data from Categories 
    * 
    * @ikac 
    */ 

    public function fetchChildren($parent, $level) { 


     $this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent='".$parent."' "); 


      foreach($this->handler->result() as $row) { 
      echo str_repeat('&nbsp; &nbsp; &nbsp; &nbsp; |-----', $level).$row->title .'<br>'; 

      $this->fetchChildren($row->title, $level+1); 
      } 

    } 

} 

像输出u将获得快速重放

Default 
    |-----Sub Category 
    |-----Test Category 1 
      |-----Seccond Test Category 1 

感谢@Eugene