Hi, I am making a little post board for myself, and I am making categories. My database is set up with a table named "categories" and three rows "id", "title", and "parentid". I will match the "parentid", to the "id" to figure out sub categories. I want to have a list of all of my categories like: Main Category 1 first sub catgegory second sub category sub sub category third sub category Main Category 2... ... How do I go about setting up the loop for this? I want this to be dynamic, to allow for unlimited sub categories, so I guess I need to do this in one or two loops, but I don't know how. +REP for help
main idea: function getcat($id,$depth){ $allid=select id from table where parent_id=$id; $depth++; for ($i=0;$i<count($allid);$i++){ echo "$allid[$i] $depth\n"; getcat($allid[$i],$depth); } } ... getcat(0,0); PHP:
You will need one loop for each level of category you want to list. So as per your example, you need to display two levels and that means two loops. While creating your tables in future, try and use PHP Object Generator phpobjectgenerator dot com. It will help you in easily managing your database activities.
My code can do it. Did you test it? Real code from one of my sites: function GetCatStruct($sid,$d){ global $CAT; $d++; $res=sql("select id,name from cat where sub_id='$sid' order by weight,name asc;"); for ($i=0;$i<@mysql_num_rows($res);$i++){ $id=mysql_result($res,$i,'id'); $CAT[$id]['name']=mysql_result($res,$i,'name'); $CAT[$id]['d']=$d; $CAT[$id]['sub_id']=$sid; GetCatStruct($id,$d); } } PHP: My sub_id is your parent_id.
Yes codesome is right. His code is recursive, which means it calls itself until there is no more sub(n) categories. "n" can be whatever level you choose. However for reason of legibility and ergonomy i would not recommand to go deeper than 2 sub levels which is way enough to categorize almost everything. With more depth you run the risk to be very redondent.