1

この正確な機能を実行しようとしていますが、ドキュメントの最後の20行のみを表示できるようにしたいですか?

    $file = fopen("/tmp/$importedFile.csv","r");
    while ($line =  fgetcsv($file))
    {
        $i++;
        $body_data['csv_preview'][] = $line;
        if ($i > 20) break;
    }
    fclose($file);

を変更してみ "r"ました$file = fopen("/tmp/$importedFile.csv","r");が、読み取りと書き込みでポインタを置く場所のバリエーションしかないようです。

これは簡単なことだと思います。謝罪いたします。

4

4 に答える 4

2

これを行う1つの方法は、を使用することSqlFileObjectです。まず、ファイルに何行あるかを知る必要があります。これは次のように計算できます。

$filename = "/tmp/$importedFile.csv";

// Create a new object for the file
$file = new SplFileObject( $filename, "r");

$lines = 0;
while ( !$file->eof()) {
   $file->fgets();
   $lines++;
}

$linesこれで、ファイルに行数があることがわかりました。次に、$lines - 20行番号を検索し、次のようにEOFまでCSVデータを読み取る必要があります。

$file->seek( $lines - 20);
while ( !$file->eof()) { 
    $body_data['csv_preview'][] = $file->fgetcsv();
}

おそらく、を計算するためのより効率的な方法があります$lines。また、を実行する前に、ファイルに20行を超えていることを確認する必要がありseek()ます$lines - 20

于 2012-07-25T13:42:28.030 に答える
1

コードは最初の20行を返します。最後の20行を変更してみてください

if($i > 20)
   array_shift($body_data['csv_preview'])
于 2012-07-25T13:39:34.210 に答える
1

私はこれを思いついた:

$file = fopen("/tmp/$importedFile.csv","r");
$start = count( file( $file ) ) - 20;
$i = 0;
while ($line =  fgetcsv($file)) {
    $i++;
    if ( $i > $start ) $body_data['csv_preview'][] = $line;
}
fclose($file);
//Body_data has now the last 20 lines.

お役に立てれば

于 2012-07-25T14:13:59.953 に答える
0

これは一方向です

$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回だけ読み取ることです。読み取り操作は、関数の中で最もコストのかかる(実行時間の)部分だと思います。

于 2012-07-25T13:41:01.280 に答える