• 0

Recursive function for tree like structure


Question

I'm struggling to get my head around this one, i've had a few attempts and failed miserably.

 

Basically I have a list of categories in a database, each with an ID. A category can have a parent category.

 

I need to output the structure in some sort of tree

 

Main category

- Child 1

- Child 2

Another category

- Child 1

- Child 2

 

Here is a very basic structure example.

 

59213c324c21b_ScreenShot2017-05-21at08_04_49.thumb.png.0105bbb0f643ad39380c850786cbe710.png

 

In this case, Fruit is a child of Food and Shoes is a child of Clothing.

 

I can manage it quite easily performing several queries but I need to do it as efficient as possible with one query and whatever is the fastest method to generate the tree like structure, either a loop or recursive function.

 

Any ideas?

 

Thanks

 

 

1 answer to this question

Recommended Posts

  • 0

There are multiple structures, for very large menus I use the nested set model explained here:

http://stackoverflow.com/questions/5916482/php-mysql-best-tree-structure

 

Otherwise it's a matter of making an sql function that grabs all direct childs of an id and call it again for all those items and again for all those items till items don't have any children.

 

In PHP it's the same, you have a $items array with id, parentId and name as example:

function awesome($parentId) {
    $tree = "";
    foreach($items as $item) {
        if($item->parenId == $parentId) {
            $tree += $item->name;
            $tree += awesome($item->id);
        }
    }
    return $tree;
}

 

Then call it:

 

$awesomeTree = awesome(NULL);

 

You can't avoid loops or recursion when you use a structure with ids and parentIds, by defining a sql function that is recursive it's not such a big problem for normal sized menus. For large menus it can become slow so I would use a different structure for that as I mentioned above, keep in mind that such structures are slower when you edit menus, there's always a trade off.

 

More info and SQL examples: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

 

This topic is now closed to further replies.
  • Posts

    • Everything's OK! 🤣🤣🤣  
    • XnView 2.52.2 by Razvan Serea XnView is freeware software that allows you to view and convert graphic files. It's very fast and easy to use. But more importantly it supports more than 500 graphics formats! Import about 500 graphic file formats Export about 50 graphic file formats Multipage TIFF, Animated GIF, Animated ICO support Image IPTC, EXIF metadata support EXIF auto rotation support IPTC editing Resize, rotate, crop support Lossless rotate & crop (jpeg) support Adjust brightness, contrast... Auto levels, contrast Modify number of colors Apply filters (blur, average, emboss, ...) Apply effects (lens, wave, ...) Fullscreen mode Slide show with effects Batch convert, batch rename Create WEB page easily Screen capture Create contact Sheet Create or edit Multi-page file (TIFF, DCX, LDF) TWAIN & WIA support (Windows only) Print support (Windows only) Drag & Drop support (Windows only) Compare image side by side Filmstrip layout 44 languages support (Windows only) XnView 2.52.2 changelog: NConvert: -xyb for JPEGli XnView vs XnView MP: XnView is the classic, lightweight version with basic features and Windows-only support. XnView MP is the modern, cross-platform version with an improved interface, better performance, and extended format support. Download: XnView 2.52.2 Installer | Standalone | ~24.0 MB (Non-commercial freeware) Download: XnView MP 1.9.2 64-bit | Standalone | ~100.0 MB Download: XnView MP 1.9.2 32-bit | Standalone | ~60.0 MB View: XnView Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Correct. You don’t buy anything that’s free (if it were).
    • Vivaldi 7.4.3684.52 by Razvan Serea Vivaldi is a cross-platform web browser built for – and with – the web. A browser based on the Blink engine (same in Chrome and Chromium) that is fast, but also a browser that is rich in functionality, highly flexible and puts the user first. A browser that is made for you. Vivaldi is produced with love by a founding team of browser pioneers, including former CEO Jon Stephenson von Tetzchner, who co-founded and led Opera Software. Vivaldi’s interface is very customizable. Vivaldi combines simplicity and fashion to create a basic, highly customizable interface that provides everything a internet user could need. The browser allows users to customize the appearance of UI elements such as background color, overall theme, address bar and tab positioning, and start pages. Vivaldi features the ability to "stack" and "tile" tabs, annotate web pages, add notes to bookmarks and much more. Vivaldi 7.4.3684.52 changelog: [Address bar] URL is searched instead of opening (VB-117198) [Chromium] Update to 136.0.7103.179 [Settings][Workspaces] Add Workspace Rule button hidden by 4th rule (VB-117181) Download: Vivaldi 64-bit | 125.0 MB (Freeware) Download: Vivaldi 32-bit | ARM64 View: Vivaldi Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Wayne Robinson earned a badge
      Week One Done
    • One Month Later
      Karan Khanna earned a badge
      One Month Later
    • Week One Done
      Karan Khanna earned a badge
      Week One Done
    • First Post
      MikeK13 earned a badge
      First Post
    • Week One Done
      OHI Accounting earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      687
    2. 2
      ATLien_0
      268
    3. 3
      Michael Scrip
      202
    4. 4
      +FloatingFatMan
      169
    5. 5
      Steven P.
      142
  • Tell a friend

    Love Neowin? Tell a friend!