簡體   English   中英

刪除csv文件php中的重復項

[英]Delete repetitions in a csv file php

我有一個csv文件,如下例所示。

SAT1002569,1,questavienedagestione,3,4,5,6,7,8,9,10,11,12,13,,15
SAT1002566,1,questavienedagestione,3,4,5,6,7,8,9,10,11,12,13,g,15
SAT1002567,1,questavienedagestione,3,4,5,6,7,8,9,10,11,12,13,h,15
SAT1002568,1,questavienedagestione,3,4,5,6,7,8,9,10,11,12,13,i,15
SAT1002569,1,questavienedagestione,3,4,5,6,7,8,9,10,11,12,13,g,15
SAT1002571,1,questavienedagestione,3,4,5,6,7,8,9,10,11,12,13,,15

我必須制作一個php腳本,該腳本首先必須找到第一個字段相同(SAT的值)的行。 如果發現兩行具有相同的第一個字段,則必須檢查兩個行中第十五個字段為空白,並且必須取消。 然后,它必須將第15個完整字段保留為書面形式。

<?php
 $RigheFileDefinitivo = explode("\n", file_get_contents("File csv/".$date.".csv")); 

    //mi ciclio il file eccomiquacisono.csv e creo un array con numero riga e contenuto riga
    foreach($RigheFileDefinitivo as $num=>$riga)
    {
        //spezzo ogni riga del file in base ad un delimitatore ovvero la ","
        $campi = explode(",", $riga);

        //dico che il contenuto numero 14 dell'array (ovvero della riga) è la data
        $NrSat = $campi[0];
        $Delimitatore = $campi[15];
        foreach($RigheFileDefinitivo as $num=>$riga)
        {
                $campi = explode(",", $riga);
                $NrSat2 = $campi[0];
                $Delimitatore = $campi[15];
                if($NrSat == $NrSat2 && $Delimitatore == ""  )
                {
                    unset($RigheFileDefinitivo[$num]);

                }
        }
    }
    file_put_contents("File csv/".$date.".csv", join("\n",$RigheFileDefinitivo));
    fclose($handle);

?>

我試圖創建腳本,但是不起作用。 我希望我已經很好地解釋了我的問題。 幫幫我下面,我將發布我編寫的腳本

使用freadcsvfputcsv 查看代碼中的注釋

if (($handle = fopen("test.csv", "r")) !== FALSE) {

    $rows = array(); //indexed by SAT value

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {                        
        if(isset($rows[$data[0]])) { 
            //if we've seen the SAT value before, 
            //keep the row with the non-empty 16th column
            if(empty($rows[$data[0]][15]) && !empty($data[15])) {
                $rows[$data[0]] = $data;
            }
        }
        else {
            //if this is the 1st time we've seen the SAT value, 
            //add it to the row as is
            $rows[$data[0]] = $data;
        }            
    }

    fclose($handle);

    //write rows to csv
    $fp = fopen('new.csv', 'w');

    foreach ($rows as $row) {
        //there still may be rows with an empty 16th column
        //for example if the csv contains a single SAT value with an empty 16th column
        //if you want to exclude these use an if statement here
        //if(!empty($row[15]))
        fputcsv($fp, $row);
    }

    fclose($fp);    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM