I thought I’d be spending a few hours creating a nice reusable way to turn a flat query result into a hierarchial array so I could use it on things like trees or HTML or whatever. When I wrote it out on paper though I felt stupid because the solution was extremely simple.

Assume you have a query result or data like this:
container1 parentA child11
container1 parentA child12
container1 parentB child13
container2 parentC child14
container2 parentC child15
and so on.

every column represents a parent of the column to its right. Duplicates in the columsn let you know which things get grouped together. The solution to turn this into a hierarchy is:

$arrTree[container][parent][child]

you can follow the same pattern indefinately, change the values and the keys as needed. The simplicity in the solution is that by using the columns as the keys it automatically creates them as unique and puts the children under them correctly. I hope this save someone else the paper epiphany :)

Share and Enjoy:
  • Digg
  • Technorati
  • Google Bookmarks
  • del.icio.us
  • Facebook
  • StumbleUpon
This entry was posted on Monday, May 18th, 2009 at 11:10 am and is filed under MySQL, PHP, Software Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a reply

Name (*)
Mail (will not be published) (*)
URI
Comment