return Unlimited subcategory array |
[eluser]Unknown[/eluser]
I'm working on a shopping cart project. I have a category table and I would like to have a dropdown with like this: Code: -Women Category table structure: Code: CREATE TABLE IF NOT EXISTS `categories` ( data is like this: Code: catid catname parentid My function is as below: Code: function getcategorylist($parentid, $space="") { When I try to echo the array value,I'm only getting the last row. ------- But when I tried to Code: echo $data['catname'] Code: $data['parentid'] = $row['parentid']; I was able to my list. But I dont want to echo the result from a model function. I would like to store the sorted hierarchy in an array and return it to the controller and then pass it to the view. Please help!!!
[eluser]Bart Mebane[/eluser]
Your $data array only saves the last row because it is local to the function and isn't preserved during the recursive calls. The array and its index need to be declared static. (This is edited. I originally made them class properties, but static is better in this case.) The array also needs to be 2-dimensional in order to hold all the categories and the information about each category. Code: function getcategorylist($parentid, $space = "") {
[eluser]Unknown[/eluser]
Thanks Bart Mebane. Quote:it would be much more efficient to just hit the database once and get all the rows, and then loop through them recursively to build the $data array.This logic has came in to my mind; but I couldn't make it. Could you please give an example with my current table? Thanks in advance.
[eluser]Bart Mebane[/eluser]
It's not too much different from what you already had, but it takes the query out of the loop. I don't have any way to verify this, so be sure to check the results. Code: function getcategorylist()
[eluser]cahva[/eluser]
Heres 2 methods in model that you can use to create an array which you can use to create category tree in view: Code: function get_categorytree($parent_id = 0) Its modified from my own code to match your categories table and did not test it. It should give you nice array of your categories something like this: Code: Array Now you have nice multidimensional array that you can use in various ways. For example you can create a helper something like in this post. |
Welcome Guest, Not a member yet? Register Sign In |