PHP super-good infinite pole classification spanning tree method
This article mainly introduced the PHP super-good infinite pole classification spanning tree method, this paper skillfully uses the reference in PHP to implement the tree generation method, more high-end than the recursive method, the need for friends can refer to the next
Are you still wasting your time and wasting your memory recursively traversing infinite pole categories, reading this article, I think you should change.
This is what I saw on the Oschina a very streamlined PHP infinite pole classification Spanning tree method, skillfully in the reference, sorting and 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 '),
2 = = Array (' id ' = = 2, ' pid ' = + 0, ' name ' = ' Zhejiang '),
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 the code code 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
)
)
)
[1] = = Array
(
[id] = 2
[PID] = 0
[Name] = Zhejiang province
)
)
The spanning tree method above can also be reduced to 5 rows:
Copy the 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 above-mentioned method of tree-shaped structure of infinite pole classification data is worthy of reference. But I think the actual use of this code is not obvious ah, you want to take out the formatted tree data or recursive AH:
Copy the code code as follows:
/**
* How to take 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);
http://www.bkjia.com/PHPjc/998353.html www.bkjia.com true http://www.bkjia.com/PHPjc/998353.html techarticle PHP super-cool infinite pole classification Spanning tree method this article mainly introduces the PHP super-good infinite pole classification spanning tree method, this paper skillfully uses the reference in PHP to implement the tree generation method, is higher than the recursive method ...