Are you still using recursive traversal of Infinitus classification that wastes time and memory? After reading this article, I think you should change it.
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.
Copy code 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 results printed below:
Copy code The code is as follows:
Array
(
[0] => Array
(
[id] => 1
[pid] =>
[name] => Anhui Province
[son] => Array
(
(
[pid] => 1
Hefei City
[name] => Hefei City
[son] => Array
(
(
[pid] => 3
)
)
)
[1] = & gt; Array
(
[pid] => 1
[name] => Anqing City
)
)
)
[1] => Array
(
[id] => 2
[pid] =>
[name] => Zhejiang Province
)
)
The above spanning tree method can also be reduced to 5 lines:
Copy 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();
}
Copy 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);