This article mainly introduces PHP’s super awesome infinite classification spanning tree method. This article cleverly uses references in PHP to implement it. The tree generation method is much more advanced than the recursive method. Friends who need it can refer to it
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' => 'Anhui Province'),
2 => array('id' => 2, 'pid' => 0, 'name' => 'Zhejiang Province'),
3 => array('id' => 3, 'pid' => 1, 'name' => 'Hefei City'),
4 => array('id' => 4, 'pid' => 3, 'name' => 'Changfeng County'),
5 => array('id' => 5, 'pid' => 1, 'name' => 'Anqing City'),
);
print_r(generateTree($items));
You can see the printed results below:
Copy the code. The code is as follows:
Array
(
[0] => Array
(
[id] => 1
[pid] => 0
[name] => Anhui Province
[son] => Array
(
[0] => Array
(
[id] => 3
[pid] => 1
[name] => Hefei City
[son] => Array
(
[0] => Array
(
[id] => 4
[pid] => 3
[name] => Changfeng County
)
)
)
[1] => Array
(
[id] => 5
[pid] => 1
[name] => Anqing City
)
)
)
[1] => Array
(
[id] => 2
[pid] => 0
[name] => Zhejiang Province
)
)
The above spanning tree method can be reduced to 5 lines:
Copy the code. 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 Infinitus 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:
Copy the code. The code is as follows:
/**
* How to get data formatted tree data
*/
$tree = generateTree($items);
Function getTreeData($tree){
foreach($tree as $t){
echo $t['name'].'
';
if(isset($t['son'])){
getTreeData($t['son']);
}
}
}
getTreeData($tree);