我如何同时从csv文件读取两行并执行操作。 我的逻辑就是这样
<?php
$i = 1;
while ($i <= 10) {
$j=1;
echo "<br>";
echo $i;
while ($j <= $i+1) {
echo $j;
$j = $j+1;
}
$i = $i+1;
}
?>
我正在尝试在读取csv文件时复制相同的逻辑,但是由于某种原因没有获得两行数据
<?php
$conn = mysqli_connect("localhost","root","","bpcl");
$filename = "test.csv";
$file = fopen($filename, "r");
$file1 = fopen($filename, "r");
$i = 1;
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) {
$j = 1;
echo $getData[1];
while ((($getData2 = fgetcsv($file1, 10000, ",")) !== FALSE) || ($j <= $i+1)) {
echo $getData2[1];
$j = $j+1;
}
$i = $i+1;
}
?>
我当前的日期数据取决于前一天,所以我在遍历整个csv时需要两行数据。在这里寻求帮助
答案 0 :(得分:2)
您不需要打开文件两次或有两个循环,您所需要做的就是在while循环中读取csv,然后在循环结束时始终将此记录存储在前几天的数据中。然后,如果设置了先前的数据,则可以使用此数据...
$conn = mysqli_connect("localhost","root","","bpcl");
$filename = "test.csv";
$file = fopen($filename, "r");
$previousDay = null;
while ($currentDay = fgetcsv($file)) {
echo "today = ".$currentDay[0].PHP_EOL;
if ( $previousDay != null ) {
echo "yesterdays = ".$previousDay[0].PHP_EOL;
}
$previousDay = $currentDay;
}
如果您想从两天的数据开始,那么在循环之前加载前几天...
$previousDay = fgetcsv($file);