列表转树一般需求是将包含完整树结构(pid=0)的列表转为树。大话题的思想在所有语言中都是相似的。设置pid为0,通过pid和id的关系,递归循环,顺藤摸瓜,查询每个节点的下属节点,找出整棵树(文末给出了两个例子)。有时候我们得到一个列表,它的数据不是从pid=0开始的,比如把大于第三层的列表转成树,或者把搜索某个关键词的结果列表转成树,那么应该怎么处理用它?思路不能从pid=0开始遍历,那我们只能遍历每一个元素。递归地为每个元素生成一个子元素列表。从列表中删除已经是其他元素的子元素的这些元素。现实(非完整整树结构表转树)phppublicstaticfunctionfragmentListToTree(&$list,&$item=null){foreach($listas$i=>&$v){if(is_null($item)){self::fragmentListToTree($list,$v);}else{if($v['pid']==$item['id']){unset($list[$i]);self::fragmentListToTree($list,$v);$item['智利'][]=$v;}}}}javascriptfragmenBuildTree:function(data){varuseIds=[]varunflatten=function(array,parent){if(parent===undefined){array.forEach(function(child){unflatten(array,child)});}else{varchildren=array.filter(function(child){returnchild?child.parentId==parent.id:'';});if(children&&children.length){parent['children']=childrenparent['叶']=假;children.forEach(function(child){useIds.push(child.id)unflatten(array,child)});}else{parent['leaf']=true;parent['children']=[]}}返回数组;}vartmp=unflatten(data)vartree=tmp.filter(function(child){for(variinuseIds){if(useIds[i]===child.id){returnfalse;}}returntrue;});returntree;}列表转树(完整树结构)phppublicstaticfunctionlistToTree($list,$pid=0){$arr=[];foreach($listas$v){if($v['pid']==$pid){$v['chile']=self::listToTree($list,$v['id']);}$arr[]=$v;}}返回$arr;}javascriptbuildTree:function(data){varunflatten=function(array,parent,tree){tree=typeoftree!=='undefined'?树:[];parent=typeofparent!=='undefined'?父母:{id:0};varchildren=array.filter(function(child){returnchild?child.parentId==parent.id:'';});如果(children&&children.length){如果(parent.id==0){tree=children;}else{parent['children']=children}parent['leaf']=false;children.forEach(function(child){unflatten(array,child)});}else{parent['leaf']=true;父母['孩子']=[]}返回树;}返回展开(数据);}
