PHP get ip:php Efficient get tree structure information

Source: Internet
Author: User
Tags foreach array get ip

In development, there are often some simple tree structure storage, such as product multi-level classification, multi-level navigation bar menu, these objects have a feature, that is, usually get the whole tree structure. There are three ways to save a tree structure in a database, the simplest of which is to point to the parent node of the current structure through a father_id. For such a small structure, we generally use the simplest way to store.
When you want to get the whole tree structure, the Internet generally use recursion, this way the code is easy to understand, but the disadvantage is that the need to perform multiple database queries, and the number of elements acquired after a few or even 0, inefficient.
In fact, in this case, all the elements can be obtained from the database, and then based on the acquired elements father_id build the tree structure, so you can solve the performance of multiple database queries. Here's how I get the functions in the multilevel navigation bar menu in the actual project.
/*
Get all the elements through the database, construct the tree structure by 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;
}
This article links http://www.cxybl.com/html/wlbc/Php/20120607/28514.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.