首页 > 解决方案 > 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);

标签: phparrayslist

解决方案


我建议使用基于文件的方法来跟踪事物。由于不依赖时区或 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 都会发生变化。


推荐阅读