我在上传csv时遇到问题,首先,我想在将重复数据或列或行输入数据库之前检查它们。我有2列/行,我想在将其插入表中之前检查两列或行上的所有数据。
注意:如果在所有两列或两行中都发现重复项,它将抛出并错误或回显该重复值,并且不会继续执行插入功能。
$stored = [];
$handle2 = fopen($_FILES["charge_file"]["tmp_name"],"r");
while(($data1 = fgetcsv($handle2,1000,",")) !==false){
$charge_emp = trim($data1[0]);
$charge_amount = trim($data1[2]);
// this is the function on checking the duplicates
if (in_array($data1[0], $stored)) { continue;}
$stored[] = $data1[0];
showDups($stored);
// this is my insert function
charges_group_entry($charge_emp,$charge_amount);
}
fclose($handle);
function showDups($array)
{
$array_temp = array();
foreach($array as $val)
{
if (!in_array($val, $array_temp))
{
$array_temp[] = $val;
}
else
{
echo 'duplicate = ' . $val . '<br />';
}
}
}
答案 0 :(得分:0)
不确定“复制在两列上找到的数据”是什么意思,因此这是两种解决方案合二为一:
$stored_emp = [];
$stored_amount = [];
$stored_pair = [];
$global_duplicate=false;
$handle2 = fopen($_FILES["charge_file"]["tmp_name"],"r");
while(($data1 = fgetcsv($handle2,1000,",")) !==false){
$charge_emp = trim($data1[0]);
$charge_amount = trim($data1[2]);
$pair = $charge_emp.' '.$charge_amount;
// this is the code for checking the duplicates separately
$duplicate=false;
if (in_array($charge_emp, $stored_emp)) {
echo 'duplicate emp = ' . $charge_emp . '<br />';
$duplicate=true;
}
if (in_array($charge_amount, $stored_amount)) {
echo 'duplicate amount = ' . $charge_amount . '<br />';
$duplicate=true;
}
if($duplicate){
$global_duplicate=true;
continue;
}
$stored_emp[] = $charge_emp;
$stored_amount[] = $charge_amount;
//use this instead if you want to check pair duplicates
if (in_array($pair, $stored_pair)) {
echo 'duplicate pair = ' . $pair . '<br />';
$global_duplicate=true;
continue;
}
$stored_pair[] = $pair;
}
//only insert values if no duplicates found
if(!$global_duplicate){
foreach($stored_emp as $nrow=>$emp){
charges_group_entry($emp,$stored_amount[$nrow]);
}
}
fclose($handle);
在任何情况下,都不需要showDups
(因为已经过滤了$stored
。