This article mainly introduces the PHP super awesome infinite Pole classification spanning tree method, this article uses the reference in PHP to realize the tree generation method skillfully, compared to the recursive method high-end many, needs the friend to be possible to refer to under
Are you still wasting time and wasting memory recursively traversing the Infinity Pole category, read the article, I think you should change it.
This is what I see on the Oschina a very concise php infinite Pole classification Spanning tree method, skillfully in the reference, collation share.
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));
You can see the results printed below:
Copy code code 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
)
)
)
[1] => Array
(
[ID] => 2
[PID] => 0
[Name] =>, Zhejiang Province
)
)
The above spanning tree method can also be reduced to 5 lines:
Copy code code 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 tree-structured method of the above infinite polar categorical data is worthy of reference. But I don't think the actual use of the code is obvious, you want to take out the formatted tree data or recursion AH:
Copy code code as follows:
/**
* How to take the 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);