递归函数如下:
/***递归获取指定分类下的子类*@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;}
作为参数传递
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;}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;}print_r(get_child_category($ar, 0));print_r(get_child_category($ar, 2));
问题已解决,非常感谢版主的热心帮助!!!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号