Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Printing categories recursivly

Status
Not open for further replies.

Petal

Programmer
Jun 8, 2001
56
NO
Hi!
I am developing a page where I have categories at many levels. I would like to always show the categories on level 1. When one category at level 1 is selected, I would like to show the categories that belong to this category and at the same time show all categories at level 1. I would like to use undetermined number of levels. And it would be different numbers of levels at every category.

I am using a mySQL databse. I have tried to make this script, but I cant make it work.

I am using a tabel with:
category_id,category_dad and category_name
category_dad is the category_id to the category that this category belongs to.

Categories at level 1 has a category_dad=0.

The code i have tried:

<?php
function write_category($category_id,$category_dad){
$sql =&quot;select category_name, category_id,category_dad from category&quot;;
$sql=$sql.&quot; where category_dad=$category_dad&quot;;
$sql=$sql.&quot; order by category_name&quot;;
$resultat = mysql_query($sql);
$resultat2 = mysql_query($sql);
$s=0;
$r=0;
while($rad = mysql_fetch_array($resultat)){
if($category_id==$category_dad){
$s=1;
$r=1;
}
if($s==0){
if(write_category($category_id,$rad[&quot;category_id&quot;])){
$r=1;
$s=1;
}
}
if($s==0){
if($category_id==$rad[&quot;category_id&quot;]){
$s=1;
$r=1;
}
}
}

if($s==1){
while($rad = mysql_fetch_array($resultat2)){
echo &quot;<tr><td ><a class='menu' target='_self' href='meny.php?category_id=&quot;.$rad[&quot;category_id&quot;].&quot;'>&quot;.$rad[&quot;category_name&quot;].&quot;</a></td></tr>&quot;;

}
}

if($r==1){
return true;
}
}
if(!isset($category_id))$category_id=0;
write_category($category_id,0);
?>
This code almost work. But i would like to print it out like this:
Airplanes
Cars
Opel
BMW
Mercedes
Motobikes

Not like this:
Opel
BMW
Mercedes
Airplanes
Cars
Motobikes

When Opel,BMW and Mercedes belong to the category Cars..

Can anybody please help me?

Jørn Arild Andenæs
jaa@jaa.no
 
You're not real big on indenting code, are you?

You're not going to be able to do a recursive output of a category and all it's immediate children in one SQL statement.

I recommend that you loop through the top-level categories, and when you get to the category whose children you want to see, perform an interior loop to output those children.

______________________________________________________________________
TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top