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_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,125
为14/04/2020,30,130
解决方案
一种方法可能是这样的:
<?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);
推荐阅读
- javascript - 如何在此面包屑模式 JSON 生成器中显示位置编号
- amazon-web-services - 如何向 Amazon Glue 表添加新分区?
- python - 无法在 Python 中运行最小的 Windows 服务
- ktor - Ktor Location API:将 JSON 映射到通用 Map 对象
- python - 在 BST 中找到最接近目标的值,但在赋值之前遇到引用的变量,即使我已经涵盖了所有情况?
- c++ - C++ 枚举作为构造函数参数
- c# - C# String 删除两个字符之间的字符
- javascript - 打字稿类约束字符串
- reactjs - 在 Sharepoint 上分享我的 react 本地主机网站
- windows - 显示和更改活动键盘映射