The PHP super powerful Infinitus classification generation tree method. This article mainly introduces the generation tree method of PHP super-awesome Infinitus classification. This article uses the reference in PHP to implement the generation method of the tree, higher than the recursive method, PHP is more powerful than the Infinitus classification tree generation method.
This article mainly introduces the PHP super-powerful Infinitus classification generation tree method. This article uses the reference in PHP to implement the tree generation method, which is much higher than the recursive method. For more information, see
Are you still using recursive traversal of Infinitus categories that wastes time and memory? after reading this article, I think you should change it.
This is a very simple PHP Infinitus classification spanning tree method I saw on OSChina. it happened to be referenced and shared.
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 '),
4 => array ('id' => 4, 'pid '=> 3, 'name' => 'changfeng County '),
5 => array ('id' => 5, 'pid '=> 1, 'name' => 'anqing '),
);
Print_r (generateTree ($ items ));
The following output is displayed:
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
[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 preceding tree generation method can also be reduced to five rows:
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 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:
The code is as follows:
/**
* How to retrieve 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 );
Ghost This article mainly introduces the PHP super awesome Infinitus classification generation tree method. This article uses the reference in PHP to implement the tree generation method, which is higher than the recursive method...