Hello i have one stupid question. But maybe is not. In database i have table categories and i have 4 cols Id, parent_id, title and description. Parent_id is child of current category.
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
Ok i know how to input data and show results; that is not problem. When i show result in table
<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>
This works great and shows child categories under under the other parent categories : Table looks like this:
1 | 1 | Main Category | description
2 | 1 | Sub Category | description
3 | 2 | Other Category | description
4 | 1 | Some Category | description
My problem is how to list all category and sub category like this
|-- Main Category
|--- Sub Category
|--- One more cat
|--Other Category
|--- Some Category
Like this

Is it possible to fetch this data using forach() ? Any example how to do this.
Thanks
Read about this http://www.sitepoint.com/hierarchical-data-database-2/. Should solve your issue.
I do this. Am working on Codeigniter framework. If any need this i will post how i fix this like on screenshot.
Just simple make model :
Model
/*
* 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(' |-----', $level).$row->title .'<br>';
$this->fetchChildren($row->title, $level+1);
}
}
}
Like output u will get
Default
|-----Sub Category
|-----Test Category 1
|-----Seccond Test Category 1
Thanks @Eugene
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With