Generate a tree structure (such as provincial and municipal), and a tree structure for provincial and municipal
<? Phpheader ("Content-type: text/html; charset = UTF-8"); function generateTree ($ 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 ;}
// Note that the key value of the array must be consistent with the id value $ items = array (1 => array ('id' => 1, 'pid '=> 0, 'name' => 'anhui province'), 2 => array ('id' => 2, 'pid '=> 0, 'name' => 'zhejiang province '), 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 "<pre> "; print_r (generateTree ($ items ));
Optimization of the above method:
<? Phpheader ("Content-type: text/html; charset = UTF-8"); function generateTree ($ items) {foreach ($ items as $ item) $ items [$ item ['pid '] ['son'] [$ item ['id'] = & $ items [$ item ['id']; return isset ($ items [0] ['son'])? $ Items [0] ['son']: array ();} // note that, the key value of the array must be consistent with the id $ items = array (1 => array ('id' => 1, 'pi' => 0, 'name' => 'anhui province '), 2 => array ('id' => 2, 'pid' => 0, 'name' => 'zhejiang province '), 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 "<pre> "; print_r (generateTree ($ items ));View Code
Result: