У меня есть файл csv с 3 столбцами (номер телефона, имя, количество). Мне нужно удалить любые повторяющиеся строки, основанные строго на столбце phonenumber.
пример:
номер имя сумма 5555551212 John Smith $ 50.00 5555551212 John Smith $ 100.00 5555551515 Jane Doe $ 125.00 5555551515 Steve Doe $ 125.90
результат:
5555551212 Джон Смит $ 50.00 5555551515 Джейн Доу $ 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);
Вы можете избежать дублирования значений столбцов в том же цикле, в котором вы строите массив, просто отслеживая $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 a duplicate so just ignore the entire row
continue;
}
// otherwise it a new phone number so store it
$phones[$phone] = true;
$rows[] = [$phone, $name, $amount];
}
fclose($handle);
}