Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从数据库中获取分层数据_Php_Mysql_Mysqli - Fatal编程技术网

Php 从数据库中获取分层数据

Php 从数据库中获取分层数据,php,mysql,mysqli,Php,Mysql,Mysqli,你好,我有一个愚蠢的问题。但也许不是。 在数据库中,我有表类别,我有4个列 Id、父项Id、标题和说明。 父项id是当前类别的子项 Id | parent_id | title | description ___________________________________________________ 1 | 1 | Main Category | description 2 | 1 | Sub Category | descri

你好,我有一个愚蠢的问题。但也许不是。 在数据库中,我有表类别,我有4个列 Id、父项Id、标题和说明。 父项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>
我的问题是如何像这样列出所有类别和子类别

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

   |--Other Category   
      |--- Some Category
像这样

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


谢谢你阅读这篇文章。应该可以解决你的问题。

我这样做。我正在研究Codeigniter框架。如果有任何需要,我会张贴我如何解决这个像截图

只需简单制作模型:

模型


谢谢@Eugene

告诉我一个,我理解网站上的教程。但我很困惑,因为他说根类别是空的。我必须为该列设置什么数据库列类型?我的类型为INT,默认值为0。在教程中,他说必须为空。父字段顶部必须为空。通常没有人使用顶级类别。它有点像一个抽象的父对象,从这里开始创建目录/类别导航。@Eugene我理解教程,但他们直接给出了左值和右值。在将节点添加为子节点或父节点时,如何知道左值和右值。
    |-- Main Category
       |--- Sub Category 
           |--- One more cat  

   |--Other Category   
      |--- Some Category
   /*
    * 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