Home > Article > Backend Development > PHP efficiently obtains tree structure information
In development, there are often some simple tree structures stored, such as multi-level classification of products, multi-level navigation bar menus, etc. One feature of these objects is that they usually obtain the entire tree structure. There are three main ways to save a tree structure in the database. The simplest one is to point to the parent node of the current structure through a father_id. For such small structures, we generally use the simplest way to store them.
When you want to obtain the entire tree structure, the recursive method is generally used on the Internet. The code of this method is simple and easy to understand, but the disadvantage is that it requires multiple database queries, and the number of elements obtained in the next few times is very small or even 0, which is very inefficient. .
In fact, when encountering this situation, you can get all the elements from the database, and then build a tree structure based on the obtained element father_id, which can solve the performance loss of executing multiple database queries. The following is a reference to the function I used to obtain the multi-level navigation bar menu in the actual project
/* 通过数据库获取所有元素,通过下面函数构造树形结构 */ 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; } }