【问题标题】:Deleting Duplicates From CSV File Wtih Multi-Columns Based On A Specific Column基于特定列从具有多列的 CSV 文件中删除重复项
【发布时间】:2016-02-13 00:22:37
【问题描述】:

我有一个包含 3 列(电话号码、姓名、金额)的 csv 文件。我需要严格根据 phonenumber 列删除所有重复的行。

示例:

号码名称金额 5555551212 约翰·史密斯 $50.00 5555551212 约翰·史密斯 $100.00 5555551515 简·多伊 $125.00 5555551515 史蒂夫·多伊 $125.90

结果:

5555551212 约翰·史密斯 $50.00 5555551515 Jane Doe $125.00

我的代码查找并删除重复项,但所有 3 列必须相同,这不是我需要的。

这是我的代码。谢谢!

$rows = [];
if (($handle = fopen($file_tmp, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    list($phone, $name, $amount) = $data;
    $phone = str_replace(['(',')','-'], '', $phone);
    $amount = str_replace(['$'], "", $amount);
    $amount = sprintf('$%.2f', $amount);

    // you can build a new array with the updated values
    $rows[] = [$phone, $name, $amount];
    // or output directly
    //echo "$phone | $name | $amount";
}
fclose($handle);
}

// if you want to save the destination with the updated information...
$fd = fopen($file_tmp, 'w');

// save the column headers
fputcsv($fd, array('number', 'name', 'amount'));


foreach ($rows as $fields) {
fputcsv($fd, $fields);
}

fclose($fd);


// array to hold all "seen" lines
$lines = array();

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

    // if the line has been seen, skip it
    if (isset($lines[$line])) continue;

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

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

// save it to a new file
file_put_contents($file_tmp, $contents);

【问题讨论】:

    标签: php csv


    【解决方案1】:

    您可以通过在自己的数组中跟踪$phone 或每次搜索整个$rows 数组来避免在构建数组的同一循环中出现重复的列值。前一种选择会更有效率。

    示例

    $rows = $phones = [];
    if (($handle = fopen($file_tmp, "r")) !== FALSE) {
    
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            list($phone, $name, $amount) = $data;
            $phone = str_replace(['(',')','-'], '', $phone);
            $amount = str_replace(['$'], "", $amount);
            $amount = sprintf('$%.2f', $amount);
            
            // track unique phone numbers here
            if (isset($phones[$phone])) {
                // it's a duplicate so just ignore the entire row
                continue;
            }
            // otherwise it's a new phone number so store it
            $phones[$phone] = true;
            $rows[] = [$phone, $name, $amount];
        }
    
        fclose($handle);
    
    }
    

    【讨论】:

    • 太棒了!效果很好。非常感谢!
    猜你喜欢
    • 2015-12-28
    • 2020-11-15
    • 2021-11-03
    • 2018-04-22
    • 2018-12-27
    • 1970-01-01
    • 2021-04-09
    • 2017-05-24
    相关资源
    最近更新 更多