PHP implements Infinite class classification, PHP implementation class classification
Copy the Code code as follows:
$area = Array (
Array (' ID ' =>1, ' name ' = ' Anhui ', ' parent ' =>0),
Array (' ID ' =>2, ' name ' = ' Haidian ', ' parent ' =>7),
Array (' ID ' =>3, ' name ' = ' Suixi County ', ' parent ' =>5),
Array (' ID ' =>4, ' name ' = ' changping ', ' parent ' =>7),
Array (' ID ' =>5, ' name ' = ' Huaibei ', ' parent ' =>1),
Array (' ID ' =>6, ' name ' = ' Chaoyang ', ' parent ' =>7),
Array (' ID ' =>7, ' name ' = ' Beijing ', ' parent ' =>0),
Array (' ID ' =>8, ' name ' = ' on ', ' parent ' =>2)
);
1. Recursive, find descendants tree
Copy the Code code as follows:
function subtree ($arr, $id =0, $lev =1) {
$subs = Array (); Descendants array
foreach ($arr as $v) {
if ($v [' parent '] = = $id) {
$v [' lev '] = $lev;
$subs [] = $v; For example, find the array (' ID ' =>1, ' name ' = ' Anhui ', ' parent ' =>0),
$subs = Array_merge ($subs, subtree ($arr, $v [' id '], $lev + 1));
}
}
return $subs;
}
$tree = subtree ($area, 0, 1);
foreach ($tree as $v) {
Echo str_repeat (', $v [' Lev ']), $v [' name '], '
';
}
2. Recursive, seek genealogy tree
Family tree applications such as breadcrumb navigation home > Phone type > CDMA phone > Public Interest PHP > recursive application
Copy the Code code as follows:
function Familytree ($arr, $id) {
$tree = Array ();
foreach ($arr as $v) {
if ($v [' id '] = = $id) {//Decide if you want to find the parent column
if ($v [' parent '] > 0) {//Parnet>0, indicating the parent column
$tree = Array_merge ($tree, Familytree ($arr, $v [' parent ']);
}
$tree [] = $v; To find an example of the land
}
}
return $tree;
}
Print_r (Familytree ($area, 8)); Shang Hai, Haidian, Beijing
2. Iterate, ask for a family tree
Copy the Code code as follows:
iterations, the efficiency is higher than recursion, the code is not much.
Find a family tree recommended iterations
function tree ($arr, $id) {
$tree = Array ();
while ($id!== 0) {
foreach ($arr as $v) {
if ($v [' id '] = = $id) {
$tree [] = $v;
$id = $v [' Parent '];
Break
}
}
}
return $tree;
}
Print_r (Tree ($area, 8));
http://www.bkjia.com/PHPjc/932494.html www.bkjia.com true http://www.bkjia.com/PHPjc/932494.html techarticle PHP implements an infinite class classification, the PHP implementation level classification copy code is as follows: $area = array (' ID ' =1, ' name ' = ' Anhui ', ' parent ' =0), array (' ID ' =2, ' name ' = ' Haidian ', ' Parent ' =7), array (' I ...