无限级分类批量导入csv-记录

 

 

 function getTreeKey($arr,$level){
        $count = count($arr)-1;
        $key = '';
        for ($i=$count;$i>=0;$i--){
            if(($arr[$i]['level']==($level-1)) && $key==''){
                $key = $i;
                continue;
            }
        }
        return $key;
    }

    function upload(){
        if(empty($_FILES['file'])){
            $this->json(1,'无数据');
        }else{
            $file = fopen($_FILES['file']['tmp_name'], 'r');
            fgetcsv($file); //去除第一行
            $arr = [];
            $num = 0;
            while ($data = fgetcsv($file)) {
                $data = eval('return ' . iconv('gbk', 'utf-8', var_export($data, true)) . ';');//编码转换一下
                $data = array_filter($data);
                if($data){
                    foreach ($data as $key=>$v){
                        $v = trim($v);
                        if($key==0 && !empty($v)){
                            $parent_key = 0;
                        }else if($key !=0 && !empty($v)){
                            //查询出上级的名称
                            $parent_key = $this->getTreeKey($arr,$key);
                        }
                        //如存在数据 不在往后面
                        if(!empty($v)){
                            $arr[$num] = ['name'=>$v,'parent_key'=>$parent_key,'level'=>$key];
                            $num++;
                            continue;
                        }
                    }
                }

            }
            if($arr){
                set_time_limit(0);
                foreach ($arr as $k=>&$v){
                    $_data = [
                        'pid'=>$v['level']==0 ? 0 : ($arr[$v['parent_key']]['id']?$arr[$v['parent_key']]['id']:0),
                        'name'=>$v['name'],
                        'level'=>$v['level']
                    ];
                    $this->db->insert('kstable',$_data);
                    $v['id'] = $this->db->insert_id();
                }
                $this->json(0,'批量导入成功');
            }else{
                $this->json(1,'无数据');
            }
        }
    }

 

posted @ 2019-08-02 14:23  大智如蠢  阅读(286)  评论(0编辑  收藏  举报