我有一个简单的275+/-行CSV文件,其中包含美国证券交易所的开市日期以及开市和收盘时间。我只关心日期,它位于每行的索引位置"0"。
例如
2022-04-01,2022-04-01 13:30:00+00:002022-04-0120:00:00+000:00
我可以找到并打印我要找的日期,我可以用它来找到之前x行和之后x行的行号(我在包含的代码中使用14天作为示例(,但我不知道如何从后两者中提取日期。如有任何帮助,我们将不胜感激。
我用来搜索给定日期的代码。
$lines = 'market_schedule.csv';
$date = '2022-04-01';
$row = 1;
if (($handle = fopen($lines, "r")) !== FALSE) {
fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row++;
if(($data[0] == $date)){
echo $data[0] . " is on line ".$row."<br />";
// $prev = [$row - 14];
// echo "Line " . $prev[0] . " is 14 lines prior.<br />";
// $fut = [$row + 14];
// echo "Line " . $fut[0] . " is 14 lines after.<br />";
}
}
fclose($handle);
}
正如@Andrea所提到的,在进行检查之前,您需要将整个文件读入内存。这里有一个假设很多的例子,可以使用一些错误检查和优化,但可以帮助您克服这个障碍。
$lines = 'market_schedule.csv';
$date = '2022-04-01';
$matchedRow = 0;
$row = 1;
$allRows = [];
if (($handle = fopen($lines, "r")) !== FALSE) {
fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row++;
$allRows[] = $data;
if ($data[0] == $date){
$matchedRow = $row;
}
}
fclose($handle);
}
$rowOffset = 14;
if ($matchedRow > 0) {
echo $allRows[$matchedRow][0] . " is on line $matchedRow <br />";
// You'll need to error check that $prev and $fut
// are valid rows
$prev = $matchedRow-$rowOffset;
$fut = $matchedRow+$rowOffset;
echo "Line " . $allRows[$prev][0] . " is $rowOffset lines prior.<br />";
echo "Line " . $allRows[$fut][0] . " is $rowOffset lines after.<br />";
} else {
echo "Didn't find a date match.<br />";
}