通过使用元素分组并通过另一个过滤来复制 CSV 文件

Duduplicate CSV File by Grouping with Element and Filtering by another

请花些时间尝试解决代码重复复制 csv 文件的问题

想法是浏览 csv 文件,删除重复项并让具有最大 id 的行

例如这个文件CSV FILE TO duduplicate

结果将是rewriting of result into csv

while (($this->lineInWork = fgetcsv($handle, 0, $delimiter)) !== false) {
        if ($index == 0) {
            if (!$this->checkHeaderFile()) {
                fclose($handle);
                return false;
            }
        } else {
            $idProject    = $this->columns[self::ID_PROJET]['index'];
            $TitleProject = $this->columns[self::Title_Project]['index'];
            $currentTitle = null;
            if ($this->lineInWork[$TitleProject] != $currentTitle)
            {
                $currentTitle = $this->lineInWork[$TitleProject];
                array_push($this->temporary_file[$currentTitle], $this->lineInWork);
            }
        }
        $index++;
    }
    fclose($handle);

问题不是重写文件,而是用正确的行构建数组

我可能会为此做两种不同的选择(假设我已经理解你的要求)。我创建了一个快速的 csv 编写器,您可能已经拥有它:

protected function saveToCsv($data, $path)
{
    $fp = fopen($path, 'w');

    foreach ($data as $fields) {
        fputcsv($fp, $fields);
    }

    fclose($fp);
}

用于筛选和排序的脚本:

# Create a storage array
$new    =   [];
# Increment array to determine header row
$i      =   0;
# Turn the csv file to array
$array  =   array_map('str_getcsv', file('original.csv'));
# Sort low to high by the ID_project
usort($array, function($a, $b){
    return ($a[0] < $b[0]);
});
# Loop the array and just re-assign over the top of each instance of value
# which will eventually assign the last value (highest)
foreach($array as $row) {
    if($i == 0) {
        # Save header to put back into the copy csv
        $header =   $row;
        $i++;
        continue;
    }
    # Assign by id so the values are unique and sortable after
    if(!isset($new[$row[2]]))
        $new[$row[2]]   =   $row;
}
# Resort by the app_id
ksort($new);
# Save the new CSV somewhere with the header merged
$this->saveToCsv(array_merge([$header], $new), 'copy.csv');