在項目中我們常常用到無限極分類:
1.在下拉選擇分類中,最簡單的是將分類組裝成二維數組,遍歷一次即可:
//獲取排列好的二維數組(帶等級)
public function GetTree($arr,$pid,$step){
global $tree;
foreach($arr as $key=>$val) {
if($val['parent_id'] == $pid) {
$flg = str_repeat('|―',$step);//重複幾次 根據等級不同重複次數不同
$val['name'] = $flg.$val['name'];
$val['level'] = $step;
$tree[] = $val;
$this->GetTree($arr , $val['id'] ,$step+1);
}
}
return $tree;
}
2.組裝成多維數組:
//分類函數 (分成帶child的多維數組)
public function buildTree($rows,$root_id){
$childs=$this->findChild($rows,$root_id);
if(empty($childs)){
return null;
}
foreach ($childs as $k => $v){
$rescurTree=$this->buildTree($rows,$v['id']);
if( null != $rescurTree){
$childs[$k]['child']=$rescurTree;
}
}
return $childs;
}
public function findChild(&$arr,$id){
$childs=array();
foreach ($arr as $k => $v){
if($v['parent_id']== $id){
$childs[]=$v;
}
}
return $childs;
}