Home >Backend Development >PHP Tutorial >Detailed explanation and file download of deduplication method in PHP
This article mainly shares with you the detailed explanation of the deduplication method and file download in PHP. During the file import process in PHP, duplicate events are often encountered, so we need to deduplicate and then download.
1. Thoughts
First set up an array to store primary keys and an empty array. Parse the file, and then check whether the primary key array in the array to be passed in exists. Set the attachment upload directory. to upload.
2. Method
If there is data in the database itself, it is easy to duplicate the imported data, so first put the primary key into a primary key array, then create a new one-dimensional array, and then Parse the csv. If it is parsed, you should merge the array defined above as the key name with the parsed csv (array_combine). Generate a new array. Then, you should determine whether the primary key in the data to be imported and the database itself are duplicated (in_array). If they are duplicated, it will show that the student number has been duplicated. If not, store the student number in the primary key array, and store the data content in the originally defined array.
3. Code
if($fp){ $fields=array('no','name','sex'); $model=M('student'); $arrno=$model->getField('no',true); $arr=array(); while(($row=fgetcsv($fp,1000,","))!==false){ $row=array_combine($fields, $row); if(in_array($row['no'],$arrno)){ echo $row['no']."学号已经存在"."<br>"; }else{ $arrno[]=$row['no']; $arr[]=$row; // dump($arr); // exit; echo $row['no']."学号已经导入"."<br>"; } if(count($arr)==1000){ $model->addAll($arr); unset($arr); } } dump($arr); if(count($arr)>0){ $model->addAll($arr); } $this->show('导入成功'); // $this->download(); }
Download
public function download(){ $file_name=$file; $file_dir="/Public/Download/"; if(!file_exists($file_dir . $file_name)){ echo "文件找不到"; exit(); }else{ $file=fopen($file_dir, $file_name,"r"); Header("Content-type:application/octet-stream"); Header("Accept-Ranges:bytes"); Header("Accept-Length:".filesize($file_dir.$file_name)); Header("Content-Disposition:attachment;filename".$file_name); echo fread($file,filesize($file_dir.$file_name)); fclose($file); exit(); } }
Related recommendations:
PHP method code to implement array deduplication
The above is the detailed content of Detailed explanation and file download of deduplication method in PHP. For more information, please follow other related articles on the PHP Chinese website!