Welcome Guest, Not a member yet? Register   Sign In
How to Create Multi level category hierarchy ( Category Tree )

i want to simply create a multilevel category hierarchy

Category table:
| id | parent_id | name
| 1 | 0 | Root
| 2 | 1 | Sub category of root
| 3 | 0 | category 1
| 4 | 3 | sub category of category 1
| 5 | 4 | sub category of first sub category of category 1

public function getCategoryTree($level = 0) {
$rows = $this->db
->where('parent_id', $level)

if (count($rows) > 0) {

foreach ($rows as $row) {
$rows = $this->getCategoryTree($row->id);

//return $rows;

echo $rows;

// output will be show as string so i have to return this string in a varriable

--Sub category of root
category 1
--sub category of category 1
----sub category of first sub category of category 1

Please guide me how i achieved this

Have a look at Joe Celko's Nested-Sets approach via google. There are a lot of php-classes out there that can provide basic operations for nested sets.
With your approach it works fine if you have a small amount of data in your database and very less deep-trees (at most from the root to a second node so that you have 3 levels)
I am writing a version easily manageable for CodeIgniter at the moment. Have a look here


and for the parent model here


PS: My provided Nested_set_Model isn't yet finished. It only supports some basic operations, but you can have a look at it and get inspired Wink Furthermore, I think all necessary queries are also written as pure SQL commands, so one can reconstruct the CI-like db-queries

Theme © iAndrew 2016 - Forum software by © MyBB