您的位置:首页 > 编程语言 > PHP开发

php中商品无限极分类

2015-11-20 23:26 531 查看
以下代码是我从网上看视频抄下来的代码(是传智播客老师写的),以备后用。

1、在商品分类模型类中加入下面代码:

                           

class CategoryModel extends Model {

                       

                    public function getAllCategories($stop_id=0){

   //组织sql
                      $sql="select * from {$this->getTableName()} order by c_sort asc";
                      //调用父类方法
                      $categories= $this->query($sql);
                      return $this->noLimitCategory($categories,0,0,$stop_id);
                   }
      
  /*无限极分类
  *@param1 array $categories,需要进行无限极分类的数组
  *@param2 int $parent_id,当前需要查询的顶级分类的id,默认为0,表示顶级分类
  *@param3 int $level 表示当前结果的级别
  *@param4 int $stop_id,需要终止查询的id
  */
                    private function noLimitCategory($categories,$parent_id=0,$level=0,$stop_id=0){
                                      //定义一个静态数组用于保存每次遍历的结果
                                       static $res= array();
                                       //遍历数组进行数据判断
                                       foreach($categories as $value){
                                        //判断数据的父级分类id
                                                  if($value['c_parent_id']==$parent_id){
                                                  //当分类的id不等于自己的id时进行遍历
                                                        if($value['c_id']!=$stop_id){
                                                                $value['level']=$level;
                                                                $res[]=$value;
                                                                //递归点:当前分类有可能有子分类
                                                                 $this->noLimitCategory($categories,$value['c_id'],$level+1,$stop_id);
                                                         }
                                                    }
                                         }
                                         //返回最终的结果
                                         return $res;
                                      }        

}

在thinkPHP模版中调用如下:

 <select name="c_id" >

               <option value="0">请选择分类</option>

               <volist name="data" id="d">

               <option value="{$d.c_id}">{:str_repeat("-",$d["level"] * 4 )}{$d.c_name}</option>

               </volist>

     </select> 

效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: