Jump to content

Archived

This topic is now archived and is closed to further replies.

mort

Categories with Sub-Categories tree, need help

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

Share this post


Link to post
Share on other sites
lol ok so maybe a little more descriptuive than that

any idea how to build the array of categories etc? anyone else done what i am looking to do could lend some pointers?

Share this post


Link to post
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..

Share this post


Link to post
Share on other sites
if you just want categories with 1 sub-category then its easy

just multiple sub-cats r proving difficult

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites
ahh mate at first glance that looks perfect!!
gonna try it out. swear i tried putting a function inside itself before and it cried lol

anyways nice one :)

Share this post


Link to post
Share on other sites
ahh dude you've only gone and done it!!

exactly what i was after, a nice little function, brilliant :)

cheers man!

Share this post


Link to post
Share on other sites

×

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.