Home > Article > Backend Development > 求个递归算法
id name pid
1 AAA 0
2 BBB 1
3 CCC 2
4 DDD 2
5 EEE 0
6 FFF 5
7 GGG 6
得出
AAA
BBB
CCC => 'CCC'
DDD => 'DDD'
EEE
FFF
GGG => 'GGG'
http://bbs.csdn.net/topics/390731721
http://bbs.csdn.net/topics/390731721
不是tree,我是想得出一个多维数组,以name为键。
http://bbs.csdn.net/topics/390731721
不是tree,我是想得出一个多维数组,以name为键。
上精华区找,徐版主写了好多
function tree($pid=0) { $res = array(); $rs = mysql_query("select * from tbl_name where pid=$pid"); while($row = mysql_fetch_assoc($rs)) { $res[$row['name']] = ($t = tree($row['id'])) ? $t : $row['name']; } return $res;}
原理是一样的,楼主把1楼链接里的代码修改下就可以满足要求了
function access($access, $arr, $pid = 0){ foreach ($access as $v) { if($v['pid'] == $pid){ $arr[$v['name']] = ($a = access($access, $arr[$v['name']], $v['id'])) ? $a : $v['name']; } } return $arr;}