Welcome to the Linux community forum and interact with 2 million technical staff. First, check the code implementation functiongenerateTree ($ items) {$ treearray (); foreach ($ itemsas $ item) {if (isset ($ items [$ item [pid]) {$ items [$ item [pid] [son] [] $ items [$ item [id];
Welcome to the Linux community forum and interact with 2 million technical staff> 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'];
Welcome to the Linux community forum and interact with 2 million technicians>
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 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 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 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 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 );
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?