PHP Two examples of infinite classification methods, PHP two categories of examples
First, recursive method
Copy CodeThe code is as follows:
$items = Array (
Array (' ID ' =>1, ' pid ' =>0, ' name ' = ' 11 '),
Array (' ID ' =>2, ' pid ' =>0, ' name ' = ' 12 '),
Array (' ID ' =>3, ' pid ' =>1, ' name ' = ' two level 21 '),
Array (' ID ' =>4, ' pid ' =>3, ' name ' = ' three level 31 '),
Array (' ID ' =>5, ' pid ' =>1, ' name ' = ' two level 22 '),
Array (' ID ' =>6, ' pid ' =>3, ' name ' = ' three level 32 '),
Array (' ID ' =>7, ' pid ' =>6, ' name ' = ' Four Level 41 '),
);
$i = 0;
function Formattree ($arr, $pid = 0) {
$tree = Array ();
$temp = Array ();
Global $i;
if ($arr) {
foreach ($arr as $k = = $v) {
if ($v [' pid '] = = $pid) {//
$temp = Formattree ($arr, $v [' id ']);
$temp && $v [' son '] = $temp;
$tree [] = $v;
}
}
}
return $tree;
}
Print_r (Formattree ($items));
second, non-recursive method
Copy CodeThe code is as follows:
function Gentree ($items) {
$tree = Array (); Well-formatted tree
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 ' = ' 11 '),
2 = = Array (' id ' = = 2, ' pid ' = 1, ' name ' = ' two ' 21 '),
3 = = Array (' id ' = = 3, ' pid ' = 1, ' name ' = ' two ' 23 '),
4 = = Array (' id ' = = 4, ' pid ' = 9, ' name ' = ' three ' 31 '),
5 = = Array (' id ' = = 5, ' pid ' = 4, ' name ' = ' four ' 43 '),
6 = = Array (' id ' = = 6, ' pid ' = 9, ' name ' = ' three ' 32 '),
7 = = Array (' id ' = = 7, ' pid ' = 4, ' name ' = ' four ' 41 '),
8 = = Array (' id ' = = 8, ' pid ' = 4, ' name ' = ' four ' 42 '),
9 = = Array (' id ' = = 9, ' pid ' = 1, ' name ' = ' two ' 25 '),
The array (' id ' = ' + ', ' pid ' = ' = ', ' name ' = ' two ', ' Level 22 '),
One-by-one and array (' id ' = = ', ' pid ' = 0, ' name ' = ' 12 '),
The array (' id ' = ' + ', ' pid ' = ' = ', ' name ' = ' two ', ' Level 24 '),
The array (' id ' = ' + ', ' pid ' = + 4, ' name ' = ' Four Level 44 '),
The array (' id ' = +, ' pid ' = ' 1, ' name ' = ' two ' 26 '),
The array (' id ' = +, ' pid ' = 8, ' name ' = ' Five Level 51 '),
+ = array (' id ' = +, ' pid ' = ' 8, ' name ' = ' Five Level 52 '),
A + = array (' id ' = ' = ', ' pid ' = ' = ' 8 ', ' name ' = ' Five level 53 '),
The array (' id ' = ' + ', ' pid ' = ' + ', ' name ' = ' six ' 64 '),
);
Print_r (Gentree ($items));
http://www.bkjia.com/PHPjc/987894.html www.bkjia.com true http://www.bkjia.com/PHPjc/987894.html techarticle PHP Two examples of infinite classification methods, PHP two classification instance one, the recursive method of copying code as follows: $items = array (' ID ' =1, ' pid ' =0, ' name ' = ' one-step '), array (' ID ' =2, ' pid ' = ...