首页 > 其他 > 详细

找家谱树(递归跟迭代)

时间:2015-02-06 16:38:59      阅读:289      评论:0      收藏:0      [点我收藏+]
递归找家谱树
<?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));

 

找家谱树(递归跟迭代)

原文:http://www.cnblogs.com/zzg521/p/4277440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!