Welcome Guest, Not a member yet? Register   Sign In
sub-categories and sub-subcategories on a associative array with CI
#6

[eluser]BrianDHall[/eluser]
I had a very similar problem on a recent project. There were top-level categories, sub-categories, sub-sub-categories, and possibly even deeper. I heard of recursion and all that but damn, I couldn't wrap my head around any of it.

So I think I found a rather simple solution instead that worked great and doesn't make my brain try to eat itself. I hope this helps as a guideline, the actual code I have is pretty site-specific.

Here's what I did as a basic guideline:

Get all the top-level categories, put them in an array.
---
Call a foreach on the array by reference, to make sure changes made to the array inside the loop are available on the next iteration.

Check to see if the category had sub-categories by calling a simple function like has_children(), a function I made that checked to see if a category had children and if so returned true.

If the category has children then add it to the end of the main array you created in step one.
---
In this way you will step through every category and subcategory. I used this method to define ever deepening levels of nested navigation for sub-categories.

Now, lets say you want to pull only sub-categories of one specific category. Then you just start the the above process with an array with only the category you want.

If you make this a function, with a little work you suddenly make it 'recursive' by making it call itself in certain instances.

So create an array, feed it to the function, if the function sees it has children then it makes an array and calls that same function - each should do some work on an outside variable.

I know this isn't exactly a full solution, but after weeks of sweating this issue it was this light-bulb moment of using an array by reference that made it all so much easier. I think I hard-coded a 4-deep loop instead of using recursive calling of a function, just because it hurt my head too much...but hey, whatever works.

You can see how it basically works by looking at the category system of the site it was done for - BukuBux.com. At the top click a category like "Professional Services". It will lead to a sub-menu system with it's subcategories - click something like "Automotive" and you'll get the top-level navigation, the sub-navigation, and then sub-sub-navigation, etc.

It's all dynamic from a database of categories that have a 'category' and a 'parent_category' field, and that's it. So I can re-arrange, add new categories, etc, and it all 'just works'.

The uri string is built similarly, for extra juicy search-engine friendly URLs.


Messages In This Thread
sub-categories and sub-subcategories on a associative array with CI - by El Forum - 09-04-2009, 02:13 PM



Theme © iAndrew 2016 - Forum software by © MyBB