Home >php教程 >php手册 >查询菜单数据后的无限级递归处理函数

查询菜单数据后的无限级递归处理函数

WBOY
WBOYOriginal
2016-06-07 11:45:14989browse

通过一次查询所有菜单数据后再从结果中整理出等级层次关系的递归函数
这个方法只要是查询的数据含有pid字段的都可以用来实现分级整理function arrayPidProcess($data,$res=array(),$pid='0'){//$level='0'){<br>     foreach ($data as $k => $v){<br>         if($v['pid']==$pid){<br>             $res[$v['id']]['info']=$v;<br>             $res[$v['id']]['child']=arrayPidProcess($data,array(),$v['id']);<br>         }<br>     }<br>     return $res;<br> }求高手对这个递归的效率进行评估,求建议更好的方法
更新一下,添加了endlevel参数,作用为限制整理级数,默认值是‘0’为全整理,设置该参数可以限制只搜索到表level字段的级数,这样有效减低不必要的系统开支function arrayPidProcess($data,$res=array(),$pid='0',$endlevel='0'){<br>     foreach ($data as $k => $v){<br>         if($v['pid']==$pid){<br>             $res[$v['id']]['info']=$v;<br>             if($endlevel!='0'){<br>                 if($v['level']==$endlevel){<br>                     $child=null;<br>                 }<br>                 else{<br>                     $child=arrayPidProcess($data,array(),$v['id'],$endlevel);<br>                 }<br>                 $res[$v['id']]['child']=$child;<br>             }<br>             else{<br>                 $child=arrayPidProcess($data,array(),$v['id']);<br>                 if($child==''||$child==null){<br>                     $res[$v['id']]['child']=null;<br>                 }<br>                 else{<br>                     $res[$v['id']]['child']=$child;<br>                 }<br>             }<br>             <br>         }<br>     }<br>     return $res;<br> }应网友要求提供的使用例子:function getMenu()
{
     $menu=M('admin_menu');
    $condition['status']='1';
    $res_menu=$menu->where($condition)->order('sort asc')->select();
    return arrayPidProcess($res_menu,array(),'0','2');
}
//查询数据整理递归函数(无限制级别)
function arrayPidProcess($data,$res=array(),$pid='0',$endlevel='0'){<br>     foreach ($data as $k => $v){<br>         if($v['pid']==$pid){<br>             $res[$v['id']]['info']=$v;<br>             if($endlevel!='0'){<br>                 if($v['level']==$endlevel){<br>                     $child=null;<br>                 }<br>                 else{<br>                     $child=arrayPidProcess($data,array(),$v['id'],$endlevel);<br>                 }<br>                 $res[$v['id']]['child']=$child;<br>             }<br>             else{<br>                 $child=arrayPidProcess($data,array(),$v['id']);<br>                 if($child==''||$child==null){<br>                     $res[$v['id']]['child']=null;<br>                 }<br>                 else{<br>                     $res[$v['id']]['child']=$child;<br>                 }<br>             }<br>             <br>         }<br>     }<br>     return $res;<br> }

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
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