【问题标题】:Remove duplicates from CSV file using PHP使用 PHP 从 CSV 文件中删除重复项
【发布时间】:2016-03-29 19:16:57
【问题描述】:

首先我加载 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 行)。

【问题讨论】:

  • 好像逻辑有问题,不是phpexcel lib或csv读写过程相关的技术问题,可以通过csv吗?如果不介意。我可以使用 csv 来玩代码。
  • 我的 2 美分:如果您有一个已经使用的数据库,为什么不导入并在那里进行进一步处理呢?数据库比将它们从 CSV 转换为 CSV 更适合数据处理...

标签: php csv duplicates


【解决方案1】:

为了读取 CSV 文件,您不必使用 PHPExcel。相反,您可以使用这样的原生 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 文件。

【讨论】:

  • 我的代码终于可以工作了。 PUTTY 可能有问题。我在不同的计算机上测试了很多次,它工作正常。它不是那么快,但这是正常的,因为我的第一个文件中有 993 行。你的解决方案真的很有趣。
  • 它不起作用。它复制相同的内容并移动到新文件。
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 2011-07-20
  • 2019-08-04
  • 1970-01-01
相关资源
最近更新 更多