标签归档:php无限级分类函数

PHP无限级分类函数

很早之前就想一套PHP无限级分类函数,供以后的项目用,今晚闲了无事,就写一个把。懒得动脑,就按以前的ASP无限级分类函数的思想写一个把。

  /*
    作者:苗启源(Miaoqiyuan.cn)
    函数:getCatagory
    功能:获得分类列表
    参数:cat_arr     -> 分类数组(Rscordset:id:分类编号,pid:上级分类,name:分类名称,childs:子分类)
          cat_pid     -> 上级分类编号
          cat_childs  -> 下级分类编号
          cat_select  -> 选择的分类
          cat_dir     -> 分类级别
    返回:返回分类列表(Option)
  */
  function getCatagory($cat_arr,$cat_pid,$cat_childs,$cat_select,$cat_dir,$format){
    if($cat_pid==0 && $format=="option"){
      echo '<option value="0">根目录</option>';
    }
    if(is_array($cat_arr)){
      foreach($cat_arr as $cat_id =>$cat){
        if($cat['pid'] == $cat_pid && strpos("," . $cat_childs . ",","," . $cat['id'] . ",") == 0){
        #if($cat['pid'] == $cat_pid){
          if($format == "option"){
            echo '<option value="'. $cat['id'] .'" '. (($cat_select == $cat['id'])?"selected":"") . '>' . $cat_dir . '┣ ' . $cat['name'] . '</option>';
          }else{
            #<li>{$cat.dir}┣<a href="?act=edt&id={$cat.id}&type=product">{$cat.name}</a></li>
            $tmp = $format;
            if(strpos($tmp,"{\$cat.dir}")>0)$tmp = str_replace("{\$cat.dir}",$cat_dir,$tmp);
            if(strpos($tmp,"{\$cat.id}")>0)$tmp = str_replace("{\$cat.id}",$cat['id'],$tmp);
            if(strpos($tmp,"{\$cat.pid}")>0)$tmp = str_replace("{\$cat.pid}",$cat['pid'],$tmp);
            if(strpos($tmp,"{\$cat.name}")>0)$tmp = str_replace("{\$cat.name}",$cat['name'],$tmp);
            if(strpos($tmp,"{\$cat.childs}")>0)$tmp = str_replace("{\$cat.childs}",$cat['childs'],$tmp);
            echo $tmp;
          }
          getCatagory($cat_arr,$cat['id'],$cat_childs,$cat_select,$cat_dir . "┃",$format);
        }
      }
    }
  }
  
  $cat_arr = Array(
    1 => Array(
      'id'     =>1,
      'pid'    =>0,
      'name'   =>'分类一',
      'childs' =>'1,2,3,4,5'
    ),
    2 => Array(
      'id'     =>2,
      'pid'    =>1,
      'name'   =>'分类二',
      'childs' =>'2,5'
    ),
    3 => Array(
      'id'     =>3,
      'pid'    =>1,
      'name'   =>'分类4',
      'childs' =>'3,4'
    ),
    4 => Array(
      'id'     =>4,
      'pid'    =>3,
      'name'   =>'分类4',
      'childs' =>'4'
    ),
    5 => Array(
      'id'     =>5,
      'pid'    =>2,
      'name'   =>'分类5',
      'childs' =>'5'
    )
  );
  
  getCatagory($cat_arr,0,'','','','<li>{$cat.dir}┣<a href="?act=edt&id={$cat.id}&type=product">{$cat.name}</a></li>');