上传文件到数据库中去掉重复值
上传文件去掉重复值
实现思路
1.将student表中的学号存到arrNo数组中(使用getFiled方法)
2.判断学号是否存在数组arrNo中(使用in_array方法)
3.如果存在输出已存在,如果不存在写入二维数组arr中,并将学号追加到arrNo数组中
实现的代码
public function import($file){
$encoding = detect_encoding($file);
//如果不是utf-8格式,则转化为utf8
if($encoding != 'UTF-8'){
$contents = file_get_contents($file);
$contents = mb_convert_encoding($contents,'utf-8',$encoding);
file_put_contents($file, $contents);
}
$fp = fopen($file, 'r');
if($fp){$files = array('no','name','sex');
$model = M('newstudent');
$arrNo = $model->getField('no',true);
$arr = array();
while(($row=fgetcsv($fp,1000,","))!==false){
$row = array_combine($files, $row);
//去掉重复值
if(in_array($row['no'],$arrNo)){
echo 'no已存在';
}else{
echo 'no不存在';
$arrNo[] = $row['no'];
$arr[] = $row;
}
if(count($arr)==1000){
$model->addAll($arr);
unset($arr);
}
}
if(count($arr)>0){
$model->addAll($arr);
}
$this->show('添加成功','utf8');
}
}