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 CodeResults:
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 ($ ...