Home >Backend Development >PHP Tutorial >在php中递归查询节点,该如何处理
在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 />
';print_r(tree($arr));<br><div class="clear"> </div>