获取相应分类id的分类树:
public static function getCategoryTree($id){ //$model=M(‘category‘); if($id>0){ $obj=self::selectTable(‘category‘,array(‘id‘=>$id),true);//$model->where(array(‘id‘=>$id))->find(); if(!is_null($obj)){ $childList=self::selectTable(‘category‘,array(‘parent_id‘=>$id));//$model->where(array(‘parent_id‘=>$id))->select(); if(!is_null($childList)){ foreach($childList as $val){ $obj[‘childList‘][]=self::getCategoryTree($val[‘id‘]); } } } if(isset($obj[‘childList‘])){ //二维数组排序 usort($obj[‘childList‘],function($a,$b){ $subtractRes=$a[‘order‘]-$b[‘order‘]; if($subtractRes<0){ return 1; }elseif($subtractRes>0){ return -1; }else{ return 0; } }); } return $obj; }else{ $rootList=self::selectTable(‘category‘,array(‘parent_id‘=>$id));//$model->where(array(‘parent_id‘=>$id))->select(); if(!is_null($rootList)){ foreach($rootList as &$val){ $val=self::getCategoryTree($val[‘id‘]); } } return $rootList; } }
递归查找无限分类的父节点:
//递归查找无限分类的父节点 public static function getCategoryParent($categoryId){ $category=self::selectTable(‘category‘,array(‘id‘=>$categoryId),true);// M(‘category‘)->where(array(‘id‘=>$categoryId))->find(); if(!empty($category)){$category[‘parent‘]=self::getCategoryParent($category[‘parent_id‘]); } return $category; }
从内存查询 表 以防止多次查库:
//从内存查询 表 以防止多次查库 private static function selectTable($tableName,array $where,$getFirst=false){ $res=array(); if(!isset(self::$tableData[$tableName])){ self::$tableData[$tableName]=M($tableName)->select(); } if(false===self::$tableData[$tableName]){ return false; } is_null(self::$tableData[$tableName]) and self::$tableData[$tableName]=array(); foreach(self::$tableData[$tableName] as $val){ $flag=true; foreach($where as $k=>$v){ if($val[$k]!=$v){ $flag=false; break; } } $flag and $res[]=$val; } $getFirst and $res=current($res); empty($res) and $res=null; return $res; }
原文:http://www.cnblogs.com/zhudongchang/p/4646442.html