【问题标题】:Get Hierarchical Data from Database从数据库中获取分层数据
【发布时间】:2013-08-06 21:05:45
【问题描述】:

您好,我有一个愚蠢的问题。但也许不是。 在数据库中,我有表 categories 并且我有 4 个 cols 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

像这样

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

谢谢

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    阅读http://www.sitepoint.com/hierarchical-data-database-2/。应该可以解决您的问题。

    【讨论】:

    • 告诉我一个,我了解网站上的教程。但是我很困惑,因为他说根类别是空的。我必须为那个 col 设置什么数据库 col 类型?我的类型是 INT,什么时候 emty 默认值为 0。在教程中他说必须为空。
    • 父字段顶部必须为空。通常没有人使用顶级类别。它是一种抽象的父类,从那里你开始创建目录/类别导航。
    • @Eugene 我了解教程,但他们直接给出了左右值。在将节点添加为子节点或父节点时如何知道左右值。
    【解决方案2】:

    我这样做。我正在研究 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);
              }
    
       }
    
    }
    

    就像你会得到的输出

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

    感谢@尤金

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 2020-10-06
      • 2013-08-29
      相关资源
      最近更新 更多