Php CSV覆盖行,如果相同日期,则附加到新行
我想将Php CSV覆盖行,如果相同日期,则附加到新行,php,csv,Php,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_nu
$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);
}
我的问题是$totalToday从API得到了不时的更新。我想记录最新的更新。所以我替换了$search=date(“d/m/Y”)
使用$search=date(“d/m/Y”),$totalToday
现在我在data.csv中有多条相同日期的记录。我想用最新数据覆盖当前日期记录,而不附加到新行。如何达到我的要求
示例数据:(第一行)
我想将
14/04/2020,26125
替换为14/04/2020,30130
一种方法可以是:
<?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);
csv是否仅在一列中包含日期?你能编辑你的问题并把data.csv的样子放几行吗?@bestprogrammerinthrold它还包含几列。日期,NewCases,TotalToday 2020年4月12日,2020年4月13日,2020年4月14日,21110日,2020年4月14日,26125因此,您可以从API获得例如2020年4月14日,18100,并希望在csv文件中将2020年4月14日,26125替换为2020年4月14日,18100。是吗?是的,没错,为你的裁判编辑的问题
<?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);