Home > Backend Development > PHP Tutorial > php多次调用递归函数

php多次调用递归函数

WBOY
Release: 2016-06-23 13:36:38
Original
1600 people have browsed it

递归函数如下:

/***递归获取指定分类下的子类*@params $categories array 全部分类的数组*@params $parent_id int 父类id 默认为顶级分类*@return $arr array 获取到的子类数组**/function get_child_category($categories,$parent_id=0){	static $arr=array();		foreach ($categories as $category){			if ($category['parent_id']==$parent_id){				$arr[]=$category;				get_child_category($categories,$category['cat_id']);			}		}	return $arr;}
Copy after login


问题描述:我想通过该函数获取指定父类下的子类,第一次调用没有问题,从第二次开始,每次调用该函数,上一次取得的结果都保存在了本次获取的数组中,比如有顶级分类A,B,C ;A类下有a1,a2,a3三个子类,B下有b1,b2,b3三个子类。第一次调用该函数获取到了A下的全部子类,第二次调用函数,想取到B下的子类b1,b2,b3,获取到的却是a1,a2,a3,b1,b2,b3,我想应该是静态变量的问题,但是如果不使用静态变量无法在递归中保存值,使用静态变量后,又出现了上述情况,我想调用一次递归函数以后,就清空上一次取得的数据,不知怎么解决,请大神赐教,不胜感激!


回复讨论(解决方案)

作为参数传递

function get_child_category($categories,$parent_id=0, $arr=array()){    foreach ($categories as $category){        if ($category['parent_id']==$parent_id){            $arr[]=$category;            $arr = get_child_category($categories,$category['cat_id'], $arr);        }    }    return $arr;}
Copy after login
为减少内存开销,可以传递引用
function get_child_category(&$categories, $parent_id=0, &$arr=array()){    foreach ($categories as $category){        if ($category['parent_id']==$parent_id){            $arr[]=$category;            get_child_category($categories, $category['cat_id'], $arr);        }    }    return $arr;}
Copy after login
调用
print_r(get_child_category($ar, 0));print_r(get_child_category($ar, 2));
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