开发过程中,经常会遇到处理无限分类数据,这里就介绍一下处理无限分类数据的两种方式,有不对的地方,还望多多指正。
//测试数据 $array=array( ['id'=>1,'parent_id'=>0,'name'=>1], ['id'=>2,'parent_id'=>0,'name'=>2], ['id'=>3,'parent_id'=>1,'name'=>3], ['id'=>4,'parent_id'=>1,'name'=>4], ['id'=>5,'parent_id'=>3,'name'=>5], ['id'=>6,'parent_id'=>3,'name'=>6] ); //递归方式 function recursion($array,$parent_id=0){ $new=[]; foreach($array as $k=>$v){ if($v['parent_id']==$parent_id){ $v['child']=recursion($array,$v['id']); if (!$v['child']) { unset($v['child']); } $new[] = $v; } } return $new; } //引用 function quote($array){ $items=array(); foreach($array as $k=>$v){ $items[$v['id']]=$v; } $tree = array(); foreach($items as $item){ if(isset($items[$item['parent_id']])){ $items[$item['parent_id']]['son'][] = &$items[$item['id']]; }else{ $tree[] = &$items[$item['id']]; } } return $tree; }
来源:https://www.cnblogs.com/yqzc/p/12345293.html