Jump to content

Categories with Sub-Categories tree, need help


mort

Recommended Posts

Hey all

I am making a category system, but cant quite figure out how to code an unlimited array of sub-categories, and also how to display them. in reality it probably wont go more than 5 or so deep, but it would be nice to make it infinite just incase

the categories table has 3 fields. cat_id, cat_name, parent_id (the cat_id of the category it's in)

if someone could just point me in the right direction i should be cool

cheers  ;D
Link to comment
Share on other sites

I would like to know how to do this as well..  Great Question..  In my example I will have the categories for Tutorials such as Photoshop, Illustrator, PHP, ASP, CSS, JavaScript, ETC...

But then some of them may have sub categories such as for Photoshop might have..

Text Effects
Photo Manipulation
Brushing
etc...

That'd be a good thing to know..
Link to comment
Share on other sites

You need a recursive function EG

[code]<?php
include 'db.php';

function listSubCats ($parent, $level = 0) {

        $sql = "SELECT category_id, name
                FROM categories
                WHERE parent = '$parent' ";
        $res = mysql_query($sql) or die(mysql_error());
       
        while (list($id, $name) = mysql_fetch_row($res)) {
       
            $indent = str_repeat('-- --', $level);
           
            echo "$indent $name<br />";
           
            listSubCats ($id, $level+1);    // now list subcats of this
       
        }
}

listSubCats(0);  // assuming top level have parent id = 0 
?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.