php - PHP:你如何只输出数组中的一行并让它记住它离开的地方?
问题描述
我在数组中有一个列表,并且只想将一行输出到 output.csv 文件中。我将每周运行一次此脚本,并希望按从上到下的顺序输出这些行。然后在最后(在本例中为第 6 周)循环回到开头。脚本如何跟踪它停止的位置以便知道接下来要处理哪一行?任何帮助表示赞赏!
$list = array
(
"some text|blue|22|sky",
"some text|red|42|ocean",
"some text|green|25|mountain",
"some text|orange|62|space",
"some text|brown|15|earth",
);
$file = fopen("output.csv","w");
foreach ($list as $line)
{
fputcsv($file,explode('|',$line));
}
fclose($file);
解决方案
我建议使用基于文件的方法来跟踪事物。由于不依赖时区或 DST,这将是更可靠和便携的方法
基于文件的方法
<?php
//read the last record
try
{
$fileName = "record.txt";
if ( !file_exists($fileName) ) {
file_put_contents("record.txt",'0'); // default - first line if run first time
}
$fp = fopen($fileName, "r+");
if ( !$fp ) {
throw new Exception('File open failed.');
}
$str = (int) fread($fp, 1); // read the first char, index to use for array
fclose($fp);
} catch ( Exception $e ) {
echo $e->getMessage();
}
$list = array
(
"some text|blue|22|sky",
"some text|red|42|ocean",
"some text|green|25|mountain",
"some text|orange|62|space",
"some text|brown|15|earth",
);
$file = fopen("output.csv","w");
$line = $list[$str];
fputcsv($file,explode('|',$line));
fclose($file);
//save what index should it read next time
$incr = intval($str)+1;
$incr = $incr == ( count($list) )? 0: $incr;
file_put_contents("record.txt",$incr);
基于日期的方法
<?php
$date = new DateTime();
$week = $date->format("W");
$list = array
(
"some text|blue|22|sky",
"some text|red|42|ocean",
"some text|green|25|mountain",
"some text|orange|62|space",
"some text|brown|15|earth",
);
$str = $week % count($list);
$file = fopen("output.csv","w");
$line = $list[$str];
fputcsv($file,explode('|',$line));
fclose($file);
基于日期的方法值得一提的一个优点是,如果在给定的一周内多次运行脚本,您将获得相同的输出,但基于文件的方法并非如此,因为每次运行脚本时,record.txt 都会发生变化。
推荐阅读
- powershell - 如何动态调用具有相同参数的 2 个不同的 cmdlet?(不是动态参数。)
- reactjs - 下拉状态未保留在 React 中
- python - 设置变量等于 sqlite3+Python 数据库条目
- c# - 在 Windows 虚拟桌面 (WVD) 中获取当前登录用户
- javascript - 在 Vue 中使用 Firestore,.where 不返回任何结果 - 但它们存在
- php - 使用 MediaWiki ClientLogin 进行登录验证
- python - 使用 Python 传递 HTML 标签
- r - 计算具有共享行的数据
- r - 获取偏函数的参数值
- python - 导入 urllib.error; ImportError: No module named error - 通过 pip 安装 r2pipe 时