0

I've been trying a lot of algorithms, including functions inside functions, and so on... But I haven't been able to solve this, hope you can help me.

I have a MySQL Table with categories, each category can have a parent category. Top categories are those whose parent is 0.

id   |   parent   |   name   |   desc 
------------------------------------------------
1    |     0      | sportwear|  test 
2    |     0      | bikes    |  test
3    |     1      | shirts   |  more tests
4    |     1      | shoes    |  ....
5    |     3      | men      | ....
6    |     3      | women    | .....

AND SO ON....

I would like to have a SELECT element with a list like this

CATEGORIES:
-sportwear
-----shirts
--------men
--------women
-----shoes
-bikes  
-morecategories
-etc

And it should have all the categories, and show them with their proper depth.

To get them All we would use something like

 SELECT * FROM categories;

To get subcategories from a specific parent we would use something like

 SELECT * FROM categories WHERE parent = PARENT-ID-HERE;

How can I make a PHP algorithm to build a select list like the one shown before?

JuanBonnett
  • 776
  • 3
  • 8
  • 26
  • Do you want a PHP script that will take the response and put it into that format? – Patrick Eaton Feb 10 '14 at 03:34
  • Yep, something simple, I am building an app with Object Oriented and MVC practices, but something simple and understandable is enough. Just a script to build a HTML Select with that format. – JuanBonnett Feb 10 '14 at 03:35
  • mysql has no support for recursive queries. you'll only ever get a flat table out of it. converting it to a tree structure is entirely up to the client-side code – Marc B Feb 10 '14 at 03:38
  • You're going to want a recursive script, that will cycle through the responses and if a parent exists move it to sit underneath. – Patrick Eaton Feb 10 '14 at 03:40
  • Yes, absoloutely, It doesn't matter if it must attack the database foreach level, I haven't been able to make a PHP algorithm to get that format – JuanBonnett Feb 10 '14 at 03:41
  • @PatrickEaton that's it Patrick, any idea? I have tried, but now my head is burning, haven't been able to achieve it. – JuanBonnett Feb 10 '14 at 03:42
  • 1
    This should be a sufficient example to help you. http://stackoverflow.com/questions/8840319/build-a-tree-from-a-flat-array-in-php – Patrick Eaton Feb 10 '14 at 03:51
  • http://stackoverflow.com/questions/18083546/mysql-recursivetree-parent-child-category try this topic – Kotzilla Feb 10 '14 at 03:57
  • It's been few hours, still trying to make this work based on those examples you gave above. Very usefull. – JuanBonnett Feb 10 '14 at 04:49

0 Answers0