簡體   English   中英

如何從php中的csv文件中刪除特定行?

[英]How to remove specific lines from a csv file in php?

我有一個像這樣的 csv 文件: 在此處輸入圖片說明

我想刪除前 3 行以及 'Data as of' 行,以便只有我的值表。

我試過array_shift($csv_data); 但它只刪除了第一行,我該怎么做?

<?php

//Modifications on csv file
$delimiter = ";"; 
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
        //Add columns with the name of pictures at the end of file : style_color.jpg 
        $data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" .$data[4].'.jpg' : '');   
        //Delete two columns with pictures
        unset($data[1]);
        unset($data[2]);
        $csv_data[] = $data;
        $row++;      
    }
    fclose($handle);
}
//delete fist 3 lines
array_shift($csv_data);

if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
    foreach ($csv_data as $data) {
        fputcsv($handle, $data, $delimiter);
    }
    fclose($handle);
}


?>

您可以使用array_slicearray_pop

$csv_data = array_slice($csv_data, 3); // this will remove first three elements
array_pop($csv_data);// this will remove last element from array

但在你的情況下,你可以跳過添加它們

$delimiter = ";";
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
        //Add columns with the name of pictures at the end of file : style_color.jpg 
        $data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : '');
        //Delete two columns with pictures
        unset($data[1]);
        unset($data[2]);
        if ($row > 3)//start adding after third row
            if (strpos($data[0], "Data as of") !== 0)//Dont add any line that starts with 'Data as of'
                $csv_data[] = $data;
        $row++;
    }
    fclose($handle);
}

如果我正確理解您的問題,您想刪除前三行,但只執行一次array_shift 最簡單的解決方案是使用 array_shift 函數三次。

//delete fist 3 lines
array_shift($csv_data);
array_shift($csv_data);
array_shift($csv_data);

至於日期的刪除:如果它是 csv 文件中的最后一個條目(或行),您可以使用array_pop($csv_data) ,它從數組中刪除最后一個條目。 如果它不是最后一行,你可以在你的 while 循環中過濾它,同時填充$csv_data數組:

if(substr($data[0], 0, 4) === "data") {
    continue;
}

$csv_data[] = $data;

這將跳過第一個單元格字符串以“data”開頭的每一行,因此它甚至不會進入 $csv_data 數組

暫無
暫無

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

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