【发布时间】: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);
【问题讨论】: