これは一方向です
$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];
}
明らかに、ここでの大きな利点は、ファイルを1回だけ読み取ることです。読み取り操作は、関数の中で最もコストのかかる(実行時間の)部分だと思います。