首页 > 解决方案 > 如果相同日期,则 CSV 覆盖行,否则附加到新行

问题描述

我想将$totalToday数据从 API 写入 csv 文件。如果当前日期不存在,则为当前日期附加新记录。我提供了以下解决方案。

$search      = date("d/m/Y");
$lines       = file('data.csv');
$line_number = false;
foreach($lines as $key => $line) {
 $line_number = (strpos($line, $search) !== FALSE);
}
if(!$line_number){
 $entry = array(date("d/m/Y"), $totalToday);
 $fp = fopen('data.csv', 'a');
 fputcsv($fp, $entry);
 fclose($fp); 
}

我的问题是 API 中的 $totalToday 不时更新。我想记录最新的更新。所以我现在替换$search = date("d/m/Y");$search = date("d/m/Y"), $totalToday我的data.csv中有多个相同日期的记录。我想用最新的数据覆盖当前日期记录而不追加到新行。如何完成我的要求

示例数据:(第一行)

    date,newCases,totalToday
    13/04/2020,21,110
    14/04/2020,26,125
    14/04/2020,30,130

我想替换14/04/2020,26,12514/04/2020,30,130

标签: phpcsv

解决方案


一种方法可能是这样的:

<?php
$search = '14/04/2020';
$other_data_from_api = array(188,102);

$lines = file('data.csv');

//Create a new array and set all dates as keys
//The latest set key would be the current
$new_arr = array();
foreach($lines as $line) {
    $exp = explode(',', $line);
    $new_arr[$exp[0]] = array($exp[1], $exp[2]);
}

/*
So in your example:
13/04/2020,21,110
14/04/2020,26,125
14/04/2020,30,130

the array $new_arr would contain:
[13/04/2020] => Array
    (
        [0] => 21
        [1] => 110
    )

[14/04/2020] => Array
    (
        [0] => 30
        [1] => 130
    )


*/


//Rewrite the whole file with values from this new array    
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {  
    $entry = $key . ',' . implode(',', $line);
    fputs($fp, $entry);
}
fclose($fp); 

您还可以:

//Rewrite the whole file with values from this new array  
//And include the actual data from the API
//(Then 188,102 would be included with the data of the $search variable)
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {  
    if ($search == $key) { 
        $entry = $search . ',' . implode(',', $other_data_from_api);
    }
    else {
        $entry = $key . ',' . implode(',', $line);
    }
    fputs($fp, $entry);
}
fclose($fp); 

推荐阅读