Home > Backend Development > PHP Tutorial > 在php中递归查询节点,该如何处理

在php中递归查询节点,该如何处理

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 11:45:39
Original
1364 people have browsed it

在php中递归查询节点
部门树下,我已经查询出所有的部门树节点id,我想根据前台传过来的根节点id,在php后台中递归出所有前台传过来的根节点的子节点,我想问问这种方式可行不,如果可行,应该怎么实现?

------解决方案--------------------

<br />1.示例1<br /><?php<br />function find_child($ar, $id='id', $pid='pid') {<br />  foreach($ar as $v) $t[$v[$id]] = $v;<br />  foreach ($t as $k => $item){<br />    if( $item[$pid] ) {<br />    	$t[$item[$pid]]['child'][] =&$t[$k];<br />      	unset($t[$k]);<br />    }<br />  }<br />  return $t;<br />}<br />$data = array(<br />	array('ID'=>1,'PARENT'=>0,'NAME'=>'kobe'),<br />	array('ID'=>2,'PARENT'=>0,'NAME'=>'jama'),<br />	array('ID'=>3,'PARENT'=>1,'NAME'=>'kobe1'),<br />	array('ID'=>4,'PARENT'=>2,'NAME'=>'jama1'),	<br />	array('ID'=>5,'PARENT'=>0,'NAME'=>'lizhi'),	<br />	array('ID'=>6,'PARENT'=>1,'NAME'=>'kobe2'),<br />);<br /><br />$c = find_child($data, 'ID', 'PARENT');<br />echo '<pre class="brush:php;toolbar:false">';<br />print_r($c);<br />?><br /><br /><br />2.示例2<br /><?php<br /><br />function find_child($ar, $id='id', $pid='pid') {<br />  foreach($ar as $v) $t[$v[$id]] = $v;<br />  foreach ($t as $k => $item){<br />    if( $item[$pid] ) {<br />    	$t[$item[$pid]]['child'][] =&$t[$k];<br />      	unset($t[$k]);<br />    }<br />  }<br />  return $t;<br />}<br />$data = array(<br />	array('ID'=>1,'PARENT'=>0,'NAME'=>'kobe'),<br />	array('ID'=>2,'PARENT'=>0,'NAME'=>'jama'),<br />	array('ID'=>3,'PARENT'=>1,'NAME'=>'kobe1'),<br />	array('ID'=>4,'PARENT'=>2,'NAME'=>'jama1'),	<br />	array('ID'=>5,'PARENT'=>0,'NAME'=>'lizhi'),	<br />	array('ID'=>6,'PARENT'=>1,'NAME'=>'kobe2'),<br />);<br /><br />$c = find_child($data, 'ID', 'PARENT');<br />echo '<pre class="brush:php;toolbar:false">';<br />print_r($c);<br />?><br />
Copy after login

------解决方案--------------------

$arr = array(
1=>array('id'=>'1','name'=>'1','pid'=>'0'),
2=>array('id'=>'2','name'=>'2','pid'=>'0'),
3=>array('id'=>'3','name'=>'11','pid'=>'1'),
4=>array('id'=>'4','name'=>'22','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 '

';print_r(tree($arr));<br><div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template