Home > Article > Backend Development > Reference implementation tree generation method in PHP
This article mainly introduces the method of generating reference implementation tree in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
Are you still using recursive traversal of Infinitus classification that wastes time and memory? After reading this article, I think you should change.
This is a very concise PHP Infinitus classification spanning tree method that I saw on OSChina. I happened to quote it and compiled it for sharing.
The code is as follows:
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' => '安徽省'), 2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'), 3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'), 4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'), 5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'), ); print_r(generateTree($items));
You can see the printed results below:
The code is as follows:
Array ( [0] => Array ( [id] => 1 [pid] => 0 [name] => 安徽省 [son] => Array ( [0] => Array ( [id] => 3 [pid] => 1 [name] => 合肥市 [son] => Array ( [0] => Array ( [id] => 4 [pid] => 3 [name] => 长丰县 ) ) ) [1] => Array ( [id] => 5 [pid] => 1 [name] => 安庆市 ) ) ) [1] => Array ( [id] => 2 [pid] => 0 [name] => 浙江省 ) )
The above spanning tree method can also be simplified Go to line 5:
The code is as follows:
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 tree-structured method of infinite classification data is worth learning from. But I think the actual use of this code is not obvious. If you want to take out the formatted tree data, you still have to recurse:
The code is as follows:
/** * 如何取数据格式化的树形数据 */ $tree = generateTree($items); function getTreeData($tree){ foreach($tree as $t){ echo $t['name'].'<br>'; if(isset($t['son'])){ getTreeData($t['son']); } } } getTreeData($tree);
Summary : The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
How to implement the persistence layer in php
php method to operate the database to determine whether the table exists
The above is the detailed content of Reference implementation tree generation method in PHP. For more information, please follow other related articles on the PHP Chinese website!