PHP: Как вы выводите только одну строку в массиве и помните, где он остановился? - PullRequest
0 голосов
/ 02 октября 2018

У меня есть список в массиве, и я хочу вывести только одну строку в файл 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);

Ответы [ 2 ]

0 голосов
/ 02 октября 2018

Более простое решение для того, что вы описали выше:

<?php

$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",
);
$filename = "output.csv";

// Getting last week line from csv file. And replacing ','s with '|'s
$last_week = str_replace(',', '|', str_replace( '"', '', trim( file_get_contents($filename) ) ) );

// Getting the array index of last week line
$last_week_index = array_search($last_week, $list);

// Checking either its first week or not, for this week index
if(is_null($last_week_index) || $last_week_index == (count($list)-1)) {
    $current_week_index = 0; // 0 in case of first week
} else {
    $current_week_index = $last_week_index + 1; // incrementing the index from last week for current week
}

// Preparing the line to write
$line_to_write = explode('|', $list[$current_week_index]);

// Closing file handler
$file = fopen($filename, "w");

// Writing to file
fputcsv($file, $line_to_write);

// Closing file handler
fclose($file);

Дайте мне знать в комментариях, если у вас есть конфликт с пониманием логики.

0 голосов
/ 02 октября 2018

Я бы посоветовал перейти на файловый подход, чтобы отслеживать вещи. Это будет более надежный и переносимый подход из-за отсутствия зависимости от часовых поясов или летнего времени

Файловый подход

<?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 будет меняться при каждом запуске сценария.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...