php - 使用 PHP 从 CSV 文件中删除重复项

标签 php csv duplicates

首先我加载PHPExcel.php

其次,我正在使用这段代码:

    $location = '/path/file.csv';



    $inputFileType = 'CSV';
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($location);

                $worksheet = $objPHPExcel->getActiveSheet();
                $list = array();
                foreach ($worksheet->getRowIterator() as $row) 
                {
                    $rowIndex = $row->getRowIndex();
                    $cellValue = $worksheet->getCell('A'.$rowIndex)->getValue();
                    array_push($list, $cellValue);       
                }
                $count = count($list);
                for ($rowIndex = $count; $rowIndex != 1; $rowIndex--) 
                {
                    $cellValue = $worksheet->getCell('A'.$rowIndex)->getValue();
                    for ($i = $rowIndex - 2; $i != 0; $i--) 
{
                        if ($list[$i] == $cellValue) 
                        {
                            $worksheet->removeRow($rowIndex);
                            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
                            $objWriter->save($location);
                            break;  
                        }
                    }
                }

所以,当第一列中有重复值时,我试图删除这些行。该代码不起作用。当我第一次用腻子运行它时,我必须等待很长时间。我中断了这个过程,然后我再次运行它。然后它运行,但在我的 csv 文件中我得到了错误的结果(重复项为 300,但我得到 -600 行)。

最佳答案

为了读取 CSV 文件,您不必使用 PHPExcel。相反,您可以使用像这样的 native php 代码:

<?php
// Array which will hold all analyzed lines
$uniqueEntries = array();
$dublicatedEntries = array();
$delimiter = ',';
$file = 'test.csv';

//Open the file
if (($handle = fopen($file, "r")) !== false) {
    // read each line into an array
    while (($data = fgetcsv($handle, 8192, $delimiter)) !== false) {
        // build a "line" from the parsed data
        $line = join($delimiter, $data);

        //If the line content has ben discovered before - save to duplicated and skip the rest..
        if (isset($uniqueEntries[$line])){
            dublicatedEntries[] = $line;
            continue;
        }

        // save the line
        $uniqueEntries[$line] = true;
    }
    fclose($handle);
}

// build the new content-data
$contents = '';
foreach ($uniqueEntries as $line => $bool) $contents .= $line . "\r\n";

// save it to a new file
file_put_contents("test_unique.csv", $contents);
?>

此代码未经测试但应该可以工作。 这将为您提供一个包含所有唯一条目的 .csv 文件。

关于php - 使用 PHP 从 CSV 文件中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434237/

相关文章:

php - 意外的文件结尾错误-删除功能修复了问题

r Shiny : How to print a message in the app after the user forgets to upload a file?

r - 如何在r中随机保留一个重复行(不是第一个重复行)

git - 如何 merge 具有不同哈希的两个相同的提交?

mysql - 为什么一张被骗的 table 只有一半大?

php - 转换 MAC 地址格式

php - 使用 pchart 和 mysql 创建图表 - 提供的示例中的正确语法

javascript - 在 Node 中运行 PHP 并将数据解析回 index.html

c# - 将 .csv 转换为数据表时的额外引号

Azure DevOps CSV 导入问题 [默认状态 'Done',关闭日期字段]