Recursively querying nodes in PHP
Department tree, I have queried all the department tree node ID, I would like to base on the foreground of the root node ID, in the background of PHP recursive out of all the foreground of the root node passed over the child node, I would like to ask this way is not feasible, if feasible, how should be implemented?
Share to: more
------Solution--------------------
1. Example 1
function Find_child ($ar, $id = ' id ', $pid = ' pid ') {
foreach ($ar as $v) $t [$v [$id]] = $v;
foreach ($t as $k = = $item) {
if ($item [$pid]) {
$t [$item [$pid]][' child '] [] =& $t [$k];
Unset ($t [$k]);
}
}
return $t;
}
$data = Array (
Array (' ID ' =>1, ' PARENT ' =>0, ' NAME ' = ' kobe '),
Array (' ID ' =>2, ' PARENT ' =>0, ' NAME ' = ' jama '),
Array (' ID ' =>3, ' PARENT ' =>1, ' NAME ' = ' kobe1 '),
Array (' ID ' =>4, ' PARENT ' =>2, ' NAME ' = ' jama1 '),
Array (' ID ' =>5, ' PARENT ' =>0, ' NAME ' = ' Lizhi '),
Array (' ID ' =>6, ' PARENT ' =>1, ' NAME ' = ' kobe2 '),
);
$c = Find_child ($data, ' ID ', ' PARENT ');
Echo '';
Print_r ($c);
?>
2. Example 2
function Find_child ($ar, $id = ' id ', $pid = ' pid ') {
foreach ($ar as $v) $t [$v [$id]] = $v;
foreach ($t as $k = = $item) {
if ($item [$pid]) {
$t [$item [$pid]][' child '] [] =& $t [$k];
Unset ($t [$k]);
}
}
return $t;
}
$data = Array (
Array (' ID ' =>1, ' PARENT ' =>0, ' NAME ' = ' kobe '),
Array (' ID ' =>2, ' PARENT ' =>0, ' NAME ' = ' jama '),
Array (' ID ' =>3, ' PARENT ' =>1, ' NAME ' = ' kobe1 '),
Array (' ID ' =>4, ' PARENT ' =>2, ' NAME ' = ' jama1 '),
Array (' ID ' =>5, ' PARENT ' =>0, ' NAME ' = ' Lizhi '),
Array (' ID ' =>6, ' PARENT ' =>1, ' NAME ' = ' kobe2 '),
);
$c = Find_child ($data, ' ID ', ' PARENT ');
Echo '';
Print_r ($c);
?>
------Solution--------------------
$arr = Array (
1=>array (' id ' = ' 1 ', ' name ' = ' 1 ', ' pid ' = ' 0 '),
2=>array (' id ' = ' 2 ', ' name ' = ' 2 ', ' pid ' = ' 0 '),
3=>array (' id ' = ' 3 ', ' name ' = ' one ', ' pid ' = ' 1 '),
4=>array (' id ' = ' 4 ', ' name ' = ' + ', ' pid ' = ' 2 '),
);
function tree ($arr) {
$t = Array ();
foreach ($arr as $v) {
if (Isset ($arr [$v [' pid ']]) {
$arr [$v [' pid ']][' child '] [] = & $arr [$v [' id ']];
}else{
$t [] = & $arr [$v [' id ']];
}
}
return $t;
}
Echo '';p Rint_r (tree ($arr));