我有一个由许多字段组成的CSV,所以我的问题是我想检查字段数据的组合是否已经存在,例如像start_date,end date,zone,package,union这样的字段在csv中不应该有相同的数据,我在cake php 4 Screen shot of csv中实现了它。
我正在使用in_array检查数据,如果数据是随机分布的,它有时会工作,但如果数据是按顺序的,它会抛出它存在于文件中的消息,而实际数据并不重复
public function validateWagerows($tmp_filename) {
$invalid_rows = array();
$invalid_row_count =array();
$invalid_row_count = 0;
$not_found_count = 0;
$unionnumbers=array();
$sd=array();
$ed=array();
$pck=array();
$zd=array();
$wr=array();
$not_found=array();
// open the file
$file = fopen($tmp_filename, "r");
if($file === false) {
$this->Flash->error('Failed to open .csv file');
return $this->redirect(['action' => 'upload']);
} else {
$header = fgetcsv($file);
while(($row = fgetcsv($file)) !== FALSE) {
foreach ($header as $k => $head) {
if($head == 'Start Date') {
$start_dates = (isset($row[$k])) ? trim($row[$k]) : '';
}
else if($head == 'End Date') {
$end_dates = (isset($row[$k])) ? trim($row[$k]) : '';
}
else if($head == 'Local Union') {
$local_union_ids= (isset($row[$k])) ? trim($row[$k]) : '';
}
else if($head == 'Package') {
$package_id = (isset($row[$k])) ? trim($row[$k]) : '';
}
else if($head === 'Zone') {
$zones_id = (isset($row[$k])) ? trim($row[$k]) : '';
}
}
if (in_array($start_dates,$sd) && in_array($end_dates,$ed) && in_array($local_union_ids, $unionnumbers) && in_array($zones_id,$zd) && in_array($package_id,$pck) )
{
$invalid_rows[$invalid_row_count]['same-data'] = "No Two or more rows with same Zone + Package +Unions within a Start and End Date can Exist in Csv ";
$result = ['invalid_row_count' => $invalid_row_count, 'invalid_rows' => $invalid_rows];
$true=$true+1;
}
$unionnumbers[]=$local_union_ids;
$sd[]=$start_dates;
$ed[]=$end_dates;
$pck[]=$package_id;
$zd[]=$zones_id;
$invalid_row_count++;
}
fclose($file);
$result = ['invalid_row_count' => $invalid_row_count, 'invalid_rows' => $invalid_rows];
print_r($result);
die;
return $result;
}
}
这将是很大的帮助,在弄清楚它或任何一个有现有的脚本可以共享
1条答案
按热度按时间e7arh2l61#
识别重复记录的常用策略是hashing。您可以创建要唯一识别的值集的编码表示,并将这些散列存储在缓冲区中,然后检查当前记录的散列是否已经在缓冲区中。这简化了逻辑,并且比其他方法更有效。