Copy 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 ' => ', ' parent ' =>2)
);
1. Recursive, find descendants tree
Copy 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 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 '], ' <br/> ';
}
2. Recursive, family tree
Family tree applications, such as breadcrumbs home > cell phone type > CDMA mobile > Public Interest PHP > recursive application
Copy Code code as follows:
function Familytree ($arr, $id) {
$tree = Array ();
foreach ($arr as $v) {
if ($v [' id '] = = $id) {//judge whether to find the parent column
if ($v [' parent '] > 0) {//parnet>0, indicating that there is a parent column
$tree = Array_merge ($tree, Familytree ($arr, $v [' parent ']));
}
$tree [] = $v; To find the upper ground as an example
}
}
return $tree;
}
Print_r (Familytree ($area, 8)); Beijing-> Haidian->
2. Iteration, Family tree
Copy code code as follows:
iterations, the efficiency is higher than recursion, the code is not much.
Find a family tree recommend 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));