新学PHP,求简化函数 用来自动计算子类栏目ID合集

浏览:441 发布日期:2015/07/20 分类:求助交流 关键字: 子类栏目ID合集
数据表是这样的
fatherid为 父级栏目
deeppath 当前层级 0 是最顶级 0下面是1级 1下面是2级
childid 当前栏目的子栏目合集 不包括当前栏目ID1 如 2,3,4
childids 当前栏目的子栏目合集 包括当前栏目ID1 如 1,2,3,4
问题来啦,如果有很多个栏目
那每次栏目被编辑时,自动根据当前栏目层级deeppath 和父级栏目 fatherid
循环计算子栏目合集 并写进数据库

我是这么写的,笨方法,自己感觉好麻烦,求简化//重置栏目子分类合集 
function ReloadeChildID($fid , $ids, $DeepPath , $DeepPathMax){
    if (empty($DeepPathMax)){ //首次执行
        $ids = M('Channel') -> field('DeepPath') -> order('DeepPath desc') -> find(); 
        $DeepPathMax = end($ids); //获取当前最大层级值
        $DeepPath = $DeepPathMax; //默认当前层级为最大层级
    }
    
    if (empty($fid)){ //首次执行
        $cids = M('Channel') -> field('ID,DeepPath,FatherID,ChildID,ChildIDs') -> where('DeepPath='.$DeepPath) -> select(); //找指定层级的栏目 默认第一次为最大
    }else //重复执行
    {
        $cids = M('Channel') -> field('ID,DeepPath,FatherID,ChildID,ChildIDs') -> where('ID='.$fid) -> select(); //找指定层级的栏目 默认第一次为最大        
    }
    
    for($i=0;$i<count($cids);$i++){ //循环处理层级
        $id = $cids[$i]['id'];
        $deeppath = $cids[$i]['deeppath'];
        $fatherid = $cids[$i]['fatherid'];
        $childid = $cids[$i]['childid'];
        $childids = $cids[$i]['childids'];
        if($deeppath == $DeepPathMax){
            //最底层 子栏目设为自己和空并保存
            $newid = $id;
            $data['ChildIDs'] = $newid;
            $data['ChildID'] = ""; 
        }
        else
        {
            //非最底层 子栏目设为自己 和 传递过来的 子栏目合集并保存
            $newid = ChannelRepeat($id . ',' . $childid . ',' . $ids); //去重复
            $newid2 = ChannelRepeat($childid . ',' . $ids);
            $data['ChildIDs'] = $newid;
            $data['ChildID'] = $newid2; 
        }
        $ids = M('Channel') -> field('ChildID,ChildIDs') -> where('id='.$id) -> save($data); //保存当前新的子栏目合集
         //是否需要向上层栏目继续循环
        if($fatherid >0){
            ReloadeChildID($fatherid,$newid,$DeepPath,$DeepPathMax);
        }
    }
}

//栏目合集去重复
function ChannelRepeat ($a){
     return implode(",",array_unique(explode(",",$a)));
}
最佳答案
评论( 相关
后面还有条评论,点击查看>>