Page 1 of 1

Unlimited multilevel category list with PHP/MySQL

Posted: Mon Dec 01, 2008 1:39 am
by mukherjiikunal
I have a table with the following structure:

cat_id (pk)
parent_cat_id
cat_desc

With the above mentioned struct we can go for a unlimited multilevel category list. This is applicable for either a ecomm, knowledge base, faq etc kinda site.

I know I have to use recursive function to get this done like the following:

Category 1
- sub cat 1
-- sub sub cat 1
-- sub sub cat 2
- sub cat 2
-- sub sub cat 3
Category 2
- sub cat 3
-- sub sub cat 4
-- sub sub cat 5

Please help me out with the idea/concept or example code re how to do this.

Re: Unlimited multilevel category list with PHP/MySQL

Posted: Mon Dec 01, 2008 2:02 am
by requinix
  1. Get list of children with a specific parent
  2. For each child (assuming there are any)
    1. Do what you want with it (like, display it)
    2. Repeat step 1

Re: Unlimited multilevel category list with PHP/MySQL

Posted: Mon Dec 01, 2008 2:42 am
by mukherjiikunal
I know the concept already. Would appreciate some sample code please!

Re: Unlimited multilevel category list with PHP/MySQL

Posted: Mon Dec 01, 2008 3:02 am
by requinix
Well then, let's see what I can come up with.

Code: Select all

function recursive($num, $indent = "") {
  1. Get list of children with a specific parent

    Code: Select all

    $children = mysql_query("SELECT num, name FROM table WHERE parent=$num");
  2. For each child (assuming there are any)

    Code: Select all

    while ($child = mysql_fetch_array($children)) {
    1. Do what you want with it (like, display it)

      Code: Select all

      echo $indent, " ", $child["name"], "<br/>\n";
    2. Repeat step 1

      Code: Select all

      recursive($child["num"], "--$indent");

    Code: Select all

    }

Code: Select all

}

Re: Unlimited multilevel category list with PHP/MySQL

Posted: Mon Dec 01, 2008 5:26 am
by mukherjiikunal
Thanks a lot for your kind help. Will try the code and revert back.

Many thanks. :P