First, check the code to implement functiongenerateTree ($ items) {$ tree = array (); foreach ($ itemsas $ item) {if (isset ($ items [$ item [& 039; pid & 039;]) {$ items [$ it
First, check the code implementation.
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 ;} $ 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'),); print_r (generateTree ($ items ));
Output result
Array ([0] => Array ([id] => 1 [pid] => 0 [name] => Anhui [son] => Array ([0] => Array ([id] => 3 [pid] => 1 [name] => Hefei [son] => Array ([0] => Array ([id] => 4 [pid] => 3 [name] => Changfeng County ))) [1] => Array ([id] => 5 [pid] => 1 [name] => Anqing ))) [1] => Array ([id] => 2 [pid] => 0 [name] => Zhejiang ))
The code is concise and refined, without recursion, and the execution speed is fast. I accidentally saw this on a website and shared it with you if it was very practical.
------------------------------------ The box below shows the question raised by the previous blogger. I don't understand what it means. sorry! -------------------------------------
The preceding tree generation method can also be reduced to five rows:
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();}The above method of tree structure of Infinitus classified data is worth learning. But I don't think the actual use of this code is obvious. You still need to recursively retrieve the formatted tree data:
/*** How to format the tree data */$ tree = generateTree ($ items); function getTreeData ($ tree) {foreach ($ tree as $ t) {echo $ t ['name'].' '; If (isset ($ t ['son']) {getTreeData ($ t ['son']) ;}} getTreeData ($ tree ); |
I don't understand why does it need to be recursively Retrieved. if I output the returned value of generateTree () as json to the front end, isn't it good?