Provides various official and user-released code examples. For code reference, you are welcome to exchange and learn the recursive functions of hierarchical relationships from the results after querying all menu data at a time.
This method can be used for hierarchical sorting as long as the queried data contains the pid field.
function arrayPidProcess($data,$res=array(),$pid='0'){//$level='0'){
foreach ($data as $k => $v){
if($v['pid']==$pid){
$res[$v['id']]['info']=$v;
$res[$v['id']]['child']=arrayPidProcess($data,array(),$v['id']);
}
}
return $res;
}
Evaluate the recursive efficiency and recommend a better method.
Updated. The endlevel parameter is added to limit the sorting level. The default value is '0'. You can set this parameter to only search for the level field of the table, this effectively reduces unnecessary system expenses
function arrayPidProcess($data,$res=array(),$pid='0',$endlevel='0'){
foreach ($data as $k => $v){
if($v['pid']==$pid){
$res[$v['id']]['info']=$v;
if($endlevel!='0'){
if($v['level']==$endlevel){
$child=null;
}
else{
$child=arrayPidProcess($data,array(),$v['id'],$endlevel);
}
$res[$v['id']]['child']=$child;
}
else{
$child=arrayPidProcess($data,array(),$v['id']);
if($child==''||$child==null){
$res[$v['id']]['child']=null;
}
else{
$res[$v['id']]['child']=$child;
}
}
}
}
return $res;
}
Examples provided at the request of netizens:
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 ');
}
// Query data sorting recursive functions (unlimited)
Function arrayPidProcess ($ data, $ res = array (), $ pid = '0', $ endlevel = '0 '){
Foreach ($ data as $ k => $ v ){
If ($ v ['pid '] ==$ pid ){
$ Res [$ v ['id'] ['info'] = $ v;
If ($ endlevel! = '0 '){
If ($ v ['level'] ==$ endlevel ){
$ Child = null;
}
Else {
$ Child = arrayPidProcess ($ data, array (), $ v ['id'], $ endlevel );
}
$ Res [$ v ['id'] ['child '] = $ child;
}
Else {
$ Child = arrayPidProcess ($ data, array (), $ v ['id']);
If ($ child = ''| $ child = null ){
$ Res [$ v ['id'] ['child '] = null;
}
Else {
$ Res [$ v ['id'] ['child '] = $ child;
}
}
}
}
Return $ res;
}
AD: truly free, domain name + VM + enterprise mailbox = 0 RMB