求个递归算法

WBOY
Release: 2016-06-23 14:00:52
Original
770 people have browsed it

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;}
Copy after login

原理是一样的,楼主把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;}
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