Generando las subcategorías para todas las categorías

Si tengo un fragmento de código como este:

$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).

Espero tener sentido.

Muchas Gracias

preguntado el 27 de agosto de 11 a las 22:08

2 Respuestas

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";
    }
}

Respondido 28 ago 11, 02:08

I didn't explain it well enough, sorry about that. But yes, you would need to loop though every level, I just didn't want to have to make a while loop for each level it have to go down. Thanks for the help! - MrE

Respondido 28 ago 11, 02:08

Cheers mate, just what I was looking for :)! - MrE

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.