Jump to content

[SOLVED] List all Sub/Sub-Sub etc.. Categories (Category Tree)


Hyaku_

Recommended Posts

Hi!
I'm trying to list category tree, but I'm having problems listing sub-sub.. categories. This is my Category field:
[code]+-------+----------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| ID    | int(11)  | NO  | PRI | NULL    | auto_increment |
| NAME  | longtext | YES  |    | NULL    |                |
| P_ID  | int(11)  | YES  |    | NULL    |                |
+-------+----------+------+-----+---------+----------------+
[/code]
This is my code So far:
[quote]function list_cat(){

$query = "SELECT * FROM CATEGORY WHERE P_ID = 0";
$query_exec = mysql_query($query);

while($data = mysql_fetch_array($query_exec)){
echo $data['NAME'] . "<BR>";

$s_query = "SELECT * FROM CATEGORY WHERE P_ID = " . $data['ID'];
$s_query_exec = mysql_query($s_query);

while($s_data = mysql_fetch_array($s_query_exec)){
echo "<font size='1'>" . $s_data['NAME'] . "</font><br>";
}


}

}[/quote]
For example I have these values into the database:
[code]+----+-----------------+------+
| ID | NAME            | P_ID |
+----+-----------------+------+
|  1 | Animals        |    0 |
|  2 | Dogs            |    1 |
|  3 | Cats            |    1 |
|  4 | Black          |    2 |
|  5 | White          |    2 |
+----+-----------------+------+
[/code]
P_ID is Categories Parrent ID. Now my function prints this:

Animals
[i]Dogs[/i]
[i]Cats[/i]

Dogs and Cats are sub-categories of Animals, but Dogs sub-categorie contains sub-sub categorie White and Black. I want to be able to print thous under Dog sub-categorie. And I want to sub-sub-sub.. categorie count to be unlimited, so I need my function to be able to always print the full categorie tree. In this case like this:

Animals
[i]Dogs[/i]
[sub][i]White
Black[/i][/sub]
[i]Cats[/i]

Any tips please?! I guess I could use arrays, but I don't have a really good plan how! Thanks!
You need a recursive function

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

function list_cat($parent, $level=0)  {
    $sql = "SELECT id, name FROM categories
            WHERE p_id = '$parent'
            ORDER BY name";
    $res = mysql_query($sql) or die(mysql_error());
    while (list($id, $name) = mysql_fetch_row($res)) {
        $indent = str_repeat('&nbsp;', $level*3);
        echo "$indent$name<br>";
        list_cat($id, $level+1);
    }
}

/**
* call the function
*/
list_cat(0);
?>
[/code]
  • 2 months later...

Archived

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

×
×
  • 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.