这是一种方式
$fileend = array();
$file = fopen("/tmp/$importedFile.csv","r");
while ($line = fgetcsv($file))
{
// we have a line, so if $fileend already contains the required number
// of lines we have to make some room.
if (count($fileend) > 20) {
$fileend=array_shift($fileend);
}
// add freshly read line to array's end
array_push($fileend,$line);
}
fclose($file);
// at this point $fileend will contain the 20 last lines of the file.
我不能向你保证它会快得令人眼花缭乱......
一种更快的方法是将行存储在固定大小的循环缓冲区中,这比听起来容易
$i=0;
while ($line = fgetcsv($file))
{
// store as linenumber modulo 20 'th element in array
$circularbuffer[$i % 20] = $line;
$i++;
}
然后阅读它
// must start reading after last written element, $i has the correct value.
// and we will read 20 times - same modulo calculation to "circulate" buffer
for ($j=$i;$j<$i+20;$j++) {
$body_data['csv_preview'][] = $circularbuffer[$j%20];
}
显然,这里最大的优势是您只读取文件一次,并且我认为读取操作是该函数迄今为止最昂贵的(执行时间)部分。