無限級分類三種方法
阿新 • • 發佈:2019-01-01
function sort($category,$parent_id=0,$level=0){ static $arr=array(); foreach($category as $k=>$v){ if($v['parent_id']==$parent_id){ $v['level']=$level; $arr[]=$v; unset($category[$k]);//已經排好等級的,從陣列中移除,提高效能 $this->sort($category,$v['id'],$level+1); } } return $arr; } function sort2($category,$parent_id=0,$level=0){ $res=array(); foreach($category as $c){ if($c['parent_id']==$parent_id){ $c['level']=$level; $arr[]=$c; $res=array_merge($arr,$this->sort($category,$c['id'],$level+1)); } } return $res; }
/** * 得到分類級數,並將他們的上下級關係,體現在返回陣列中 * @param unknown $category * @param number $parent_id * @param number $level * @return multitype:array */ function category($category,$parent_id=0,$level=0){ $arr=array(); foreach($category as $k=>$v){ if($v['parent_id']==$parent_id){ $v['level']=$level; $v['child']=$this->category($category,$v['id'],$level+1); $arr[]=$v; } } return $arr; }