Order Sub-Categories under Parent

Discussion in 'PHP' started by killaklown, Aug 19, 2006.

  1. #1
    How will i be able to order my sub-categories under my parent?

    Right now they show up as:

    -Parent 1
    -Parent 2
    -Parent 3
    -Parent 4
    ---Sub-Categories of 1
    ---Sub-Categories of 2
    ---Sub-Categories of 3
    ---Sub-Categories of 4

    My code is:

    
        $cat.='<select size="1" name="category" size="36" maxlength="255">';
        $cat.='<OPTION VALUE="___" selected>Select A Category</OPTION>';
        $sql_query_cat = "SELECT * FROM categories ORDER BY parent ASC";
        //store the SQL query in the result variable
        $result_cat = mysql_query($sql_query_cat);
        if(mysql_num_rows($result_cat))
        {
        //output as long as there are still available fields
        while($row = mysql_fetch_array($result_cat))
        {
    	 $parent = stripslashes($row[parent]);
    	 $categ = $row[title];
         $categ = stripslashes($categ);
    	 if($parent=='0'){
    	$cat.='<option>-'.$categ.'</option>';
     }else{
     	$cat.='<option>---'.$categ.'</option>';
    	}
        }
    	}
        $cat.='</select>';
    
    PHP:

    The table contains 'id', 'title', 'parent'
     
    killaklown, Aug 19, 2006 IP
  2. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This function should do the trick:

    
    function build_category_tree( $id, $level, $defaultID)
    {
    $printme = "";
    $categories = mysql_query("SELECT * FROM categories WHERE PARENT = $id ORDER BY name");
    if(count($categories) < 1) { return $printme; }
    while ($category = mysql_fetch_object($categories) )
    	{
    	if($id == 0) { $printme .= "<option>---------------------------</option>\n"; }
    	$printme .= "<option value=\"" . $category->id . "\"";
    	if($defaultID == $category->id) { $printme .= " selected=\"selected\""; }
    	$printme .= " \">";
    	$printme .= str_repeat(" &gt; ", $level) .  $category->name . "</option>\n";
    	$printme .= build_category_tree( $category->id, $level + 1, $defaultID);
    	}
    
    return $printme;
    }
    
    Code (markup):
     
    clancey, Aug 19, 2006 IP