使用基于特定列

时间:2015-11-11 19:40:10

标签: php csv

我有一个包含3列的csv文件(phonenumber,name,amount)。我需要严格根据phonenumber列删除任何重复的行。

示例:

号码名称金额 5555551212 John Smith $ 50.00 5555551212 John Smith $ 100.00 5555551515 Jane Doe $ 125.00 5555551515 Steve Doe $ 125.90

结果:

5555551212 John Smith $ 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);

1 个答案:

答案 0 :(得分:0)

您可以通过在自己的数组中跟踪$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);

}