PHP efficient access to tree structure information
In the development, there are often some simple tree structure storage, such as product multilevel classification, multi-level navigation bar menu, and so on, these objects have a feature, is usually to get the whole tree structure. There are three ways to save a tree structure in a database, and the simplest one is to point to the parent node of the current structure through a father_id. For such a small structure, we usually store it in the simplest way.
When you want to get the whole tree structure, the web is generally recursive, this way the code is easy to understand, but the disadvantage is that you need to perform multiple database queries, and the number of elements acquired in the subsequent few or even 0, the efficiency is poor.
In fact, in this case, all the elements can be retrieved from the database, and then based on the acquired element father_id build tree structure, so that can be done to perform multiple database queries performance loss. Here's a list of functions that I get from the multi-level navigation bar menu in my actual project.
/* Gets all the elements through the database, constructs a tree structure with the following function */private function Gettree ($menus) { $id = $level = 0; $menuobjs =array (); $tree = Array (); $notrootmenu =array (); foreach ($menus as $menu) { $menuobj =new stdClass (); $menuobj->menu= $menu; $id = $menu [' id ']; $level = $menu [' father_id ']; $menuobj->nodes = Array (); $menuobjs [$id]= $menuobj; if ($level) {$ Notrootmenu[]= $menuobj;} else {$tree [] = $menuobj;} } foreach ($notrootmenu as $menuobj) {$menu = $menuobj->menu; $id = $menu [' id ']; $level = $menu [' father_id ']; $MENUOBJS [$ Level]->nodes[]= $menuobj;} return $tree; }}
My Weibo address: Http://weibo.com/jameren, welcome to the attention of all.
By the way, make an ad:
Reference
[email protected], can be used on PC and mobile phone, no file type and size restrictions, transmission speed, file never lost, come together experience it! By registering with the invitation link below, you and I will have an extra 256MB of cool disk space! Http://t.cn/aNLZje