简体   繁体   中英

Generating the sub-categories for all categories

If I have a piece of code like this:

$get_categories = mysql_query("SELECT * FROM categories");
$categories = mysql_fetch_assoc($get_categories);

The category table contains all the different categories and their sub categories and their sub categories etc.

How can I make some php code which generate a list like this:

Main Category
-Sub Category
- -Sub Sub Category
- -Sub Sub Category
- - -Sub Sub Sub Category etc
-Sub Category
Main Category

A list of all categories and their sub categories and their sub categories and so on.

I cannot see how I am able to do with without making a while loop for each sub category level (which is stupid as I would then have to create 50 levels to make sure it works with if I have 50 levels of sub categories).

I hope I make sense.

Thanks

I cannot think of a solution for how not to loop through every level. If you don't use meta-data and a static structure the recursion is inevitable.

A table structure like this would allow a arbitrary category tree.

CREATE TABLE `categories` (
    `id` int(8) NOT NULL auto_increment,
    `parent_id` int(8) NOT NULL,
    `name` varchar(25) NOT NULL
    PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

INSERT INTO categorires (parent_id,name) VALUES (0,'Hardware');
INSERT INTO categorires (parent_id,name) VALUES (1,'Harddrives');
INSERT INTO categorires (parent_id,name) VALUES (2,'IDE');
INSERT INTO categorires (parent_id,name) VALUES (2,'SATA');
INSERT INTO categorires (parent_id,name) VALUES (0,'Memory');

Renders structure:

+Hardware
    +Harddrives
        +IDE
        +SATA
+Memory

PHP:

function renderCategoryTree($categories){
    foreach($categories as $category){
        if(is_array($category))
            renderCategoryTree($category);
        else
            echo "+$category";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM