JavaScript版:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript"> var arr = { '1' : 0, '2' : 1, '3' : 0, '4' : 1, '5' : 2, '6' : 0, '7' : 6, '8' : 5, '9' : 8, '10' : 8 }; var id,i=0; /** * tree = [{ id:,pid:,level: }] */ var tree = []; for(var key in arr){ if(arr[key]==0){ // 属于顶级 tree.push({id:key,pid:arr[key],level:0}); }else{ id = key; i = 0; while(arr[id]){ id = arr[id]; i++; } tree.push({id:key,pid:arr[key],level:i}); } } console.log(tree); </script> </body> </html>
PHP版
<?php /** * [infiniteOrder 无限级分类] * @author 江波 * @date 2016-12-28 * @param [string] $list [分类列表] * @param [string] $field_pid [用于分类的字段名称] * @param [string] $pval [顶层结束值] * @return [array] [分类之后的列表] * @throws */ function infiniteOrder(&$list, $field_pid = 'pid', $pval = 0){ // 用于缓存结果 $arr = array(); foreach($list as $key => $val){ $i = 0; if($val[ $field_pid ] != $pval){ // 不属于顶级 $id = $val[ $field_pid ]; // 当循环至顶级结束 while($val[ $id ] != $pval){ $id = $val[ $id ]; $i++; } } $val['_level'] = $i; $arr[] = $val; } return $arr; }
public function getInfiniteList(){ $arr = array(); // 分类列表 $list = $this->select(); foreach($list as $k1 => $v1){ $arr[ $v1['id'] ] = $v1['pid']; } $i = 0; foreach($arr as $k2 => $v2){ $level = 0; $pid = $v2['pid']; if($pid != 0){ // 不属于顶级 $level++; // 当循环至顶级结束 while($arr[$pid] != 0){ $pid = $arr[$pid]; $level++; } } $list[$i]['_level'] = $level; $i++; } return $list; }