Re: Unlimited Categories and Sub-Categories
| From: | Jay Greenspan | Date: | Sun, 10 Sep 2000 00:34:37 +0000 |
| Subject: | Re: Unlimited Categories and Sub-Categories | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-16027@lists.php.net to get a copy of this message | ||
> Thanks, but how would I perform the select query? If possible, please
>include a code sample.
I think this needs to be done with a recursive function. Say you have a
table
like this:
category_id, parent_id, cat_desc
1,1, cat1
2,1, next category
3, 2, third category
4, 2, fourth category
So above cat_id 1 is a 'top-level category', and you know this because the
category and partent_id are the same. cat_id 2 is a child of cat_id 1
and both three and four are childre of cat_id 2.
To get an entire listing of these, say indented with <ul> and <li> tags, you
you need to do something like the following. This could use static
variables,
for the sake of this example I didn't bother.
function print_recursive($category_id = 1, $counter=1)
{
echo "<ul>";
if ($counter==1)
{
/* the first time through you want a top-level list */
$query = "select category_id, parent_id, cat_desc from recur
where category_id = parent_id";
}
else
{
/* make sure to exclude top-level rows, or this will loop endlessly
*/
$query = "select * from recur where parent_id = $category_id
and category_id != parent_id";
}
$result = mysql_query($query);
while(list($category_id, $parent_id, $cat_desc) =
mysql_fetch_array($result) )
{
echo "<li>" . $category_id . $parent_id . $cat_desc .
"<br>";
/* the function now calls iteslf with a new category_id */
print_recursive($category_id, ++$counter);
}
echo "</ul>";
}
print_recursive();
Recursion can be a pretty tough topic at first. If you don't undersatnd it
immediately, follow it through and see what happens to the variables with
each
iteration.
HTH,
jay