Build tree structure (such as provinces and cities), tree-type structure and provinces _php tutorial

Source: Internet
Author: User

Spanning tree structure (e.g. provinces and cities), tree-like structure, urban area



PhpHeader("content-type:text/html; Charset=utf-8 ");functionGeneratetree ($items){ $tree=Array(); foreach($items as $item){ if(isset($items[$item[' PID ']])){ $items[$item[' PID '] [' son '] [] = &$items[$item[' ID ']]; }Else{ $tree[] = &$items[$item[' ID ']]; } } return $tree;}
It should be noted that the key value of the array must be consistent with the ID value
$items=Array( 1 =Array(' id ' = 1, ' pid ' = + 0, ' name ' = ' Anhui '), 2 =Array(' id ' = 2, ' pid ' = + 0, ' name ' = ' Zhejiang '), 3 =Array(' id ' = 3, ' pid ' = 1, ' name ' = ' Hefei '), 4 =Array(' id ' = 4, ' pid ' = 3, ' name ' = ' Changfeng County '), 5 =Array(' id ' = 5, ' pid ' = 1, ' name ' = ' Anqing '),);Echo"
"; Print_r (Generatetree ($items));

Optimization of the above method:

PhpHeader("content-type:text/html; Charset=utf-8 ");functionGeneratetree ($items){ foreach($items as $item) $items[$item[' PID '] [' son '] [$item[' ID ']] = &$items[$item[' ID ']]; return isset($items[0] [' son ']) ?$items[0] [' Son ']:Array();}//It should be noted that the key value of the array must be consistent with the ID$items=Array( 1 =Array(' id ' = 1, ' pid ' = + 0, ' name ' = ' Anhui '), 2 =Array(' id ' = 2, ' pid ' = + 0, ' name ' = ' Zhejiang '), 3 =Array(' id ' = 3, ' pid ' = 1, ' name ' = ' Hefei '), 4 =Array(' id ' = 4, ' pid ' = 3, ' name ' = ' Changfeng County '), 5 =Array(' id ' = 5, ' pid ' = 1, ' name ' = ' Anqing '),);Echo"
"; Print_r (Generatetree ($items));
View Code

Results:

http://www.bkjia.com/PHPjc/1128373.html www.bkjia.com true http://www.bkjia.com/PHPjc/1128373.html techarticle Generate tree structure (such as provinces and cities), tree-type structure of the provinces and cities, PHP header ("content-type:text/html; Charset=utf-8 "); function Generatetree ($items) {$tree = array (); foreach ($ ...

  • 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.