1 ----------web design--------- 0 -------->(0, means no parent category)
2 ----------CSS--------------- ---1
... ... ...
this is my category structure
I may gonna have more than 3 lvls . I need to show all the categories to let visitors to pick in the drop down box.
I select * from category, now i need to sort the result based on parent and child, also from top lvl to lower lvl.
I am thinking about using recusive function. but just cannot get it. please help me out, if you could write me some code, or if theres another way to do it without recusive that gonna be great. recursive function gonna give alot trouble if we dont use it carefully.
here's my code,but it doesnt work, i couldn't even make it recursive.
pid is parent id, and catlist is array of all categories.
function categorysort($pid, $catlist)
for ($i=0; $i<count($catlist); $i++)
if ($pid == $catlist[$i]['parentid'])
$categorylist = $catlist[$i];
Where does your $catlist comes from?
How do you generate your catlist?
I assume since you're getting your $catlist from the database, why don't you generate the sorting at the same time while retrieving instead of retrieving from the database and then drop the list to a function and loop through the sorting again? Kinda waste of resource unless you're trying to really seperate view and model respectively.
I'm saying this because that's the way I do and if you are willing to switch, I can teach you my way of doing it. Also, to optimize the queries for these kind of categories level issue, I prefer to add another flag field to indicate whether or not a parent does indeed have childrens. If this flag tells me ==1, I'll query for more children.
Pass $catlist by reference, not by value (function something(&$catlist)).
Record a depth of the category to the database (how deep it is in the parent-child relation so you don't have to have lots of loops, meaning is it the first, second, third child etc.). Should get you going somewhere without someone posting the entire code. Good luck
Horizon's method will not work unfortunately, because it doesn't take into account the parent/child relationship, and further makes the assumption that parent IDs are ordered in the relationship as well. These assumptions cannot be made.
circlical - hosting software development forums * blog