码迷,mamicode.com
首页 > 其他好文 > 详细

找家谱树(递归跟迭代)

时间:2015-02-06 16:41:42      阅读:145      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!