递归找家谱树<?php header("Content-type:text/html;charset=utf-8"); /* ** 递归查找家谱树 */ $area = array( array(‘id‘=>1,‘name‘=>‘安徽‘,‘parent‘=>0), array(‘id‘=>2,‘name‘=>‘海淀‘,‘parent‘=>7), array(‘id‘=>3,‘name‘=>‘濉溪县‘,‘parent‘=>5), array(‘id‘=>4,‘name‘=>‘昌平‘,‘parent‘=>7), array(‘id‘=>5,‘name‘=>‘淮北‘,‘parent‘=>1), array(‘id‘=>6,‘name‘=>‘朝阳‘,‘parent‘=>7), array(‘id‘=>7,‘name‘=>‘北京‘,‘parent‘=>0), array(‘id‘=>8,‘name‘=>‘上地‘,‘parent‘=>2) ); function famely($area,$id){ static $tree = array(); //加上static foreach ($area as $v) { # code... if ($v["id"] == $id) { # code... $tree[] = $v; famely($area,$v["parent"]); //调用自身(不用判断parent id是否存在,因为前面if已经判断了) } } return $tree; } print_r( famely($area,8) ); ?>
迭代找家谱树(一般建议用迭代找)
/* * 迭代找出家谱树 */ $area = array( array(‘id‘=>1,‘name‘=>‘安徽‘,‘parent‘=>0), array(‘id‘=>2,‘name‘=>‘海淀‘,‘parent‘=>7), array(‘id‘=>3,‘name‘=>‘濉溪县‘,‘parent‘=>5), array(‘id‘=>4,‘name‘=>‘昌平‘,‘parent‘=>7), array(‘id‘=>5,‘name‘=>‘淮北‘,‘parent‘=>1), array(‘id‘=>6,‘name‘=>‘朝阳‘,‘parent‘=>7), array(‘id‘=>7,‘name‘=>‘北京‘,‘parent‘=>0), array(‘id‘=>8,‘name‘=>‘上地‘,‘parent‘=>2) ); function fameletree($area,$id){ $tree = array(); while ($id !== 0) { //此处while循环 foreach ($area as $v) { # code... # code... if($v["id"] == $id){ $tree[] = $v; $id = $v["parent"]; //把parent id赋给$id break; } } } return $tree; } print_r(fameletree($area,8));
时间: 2024-10-17 13:17:06