Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Last active March 30, 2016 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurozumi/b4bc1005b3f367989f7f8eefd7629765 to your computer and use it in GitHub Desktop.
Save kurozumi/b4bc1005b3f367989f7f8eefd7629765 to your computer and use it in GitHub Desktop.
【PHP】CSVファイルの任意のカラムの重複したデータを削除する方法
<?php
// CSVファイル
$read = new \SplFileObject("list.csv", "r");
// 一時ファイル
$temp = new \SplFileObject("temp.csv", "w");
// ファイルの終端に達するまでループする
while(! $read->eof())
{
// ここに重複チェック用のデータを追加していく
static $list = [];
// ファイルポインタから行を取得し、CSVフィールドを処理する
$line = $read->fgetcsv();
// CSVフィールドの1列目の値が$listにあれば次の行へ
if(in_array($line[0], $list))
continue;
// 上記、なければ一時ファイルに書き込み
if ($temp->flock(LOCK_EX)) {
$temp->fwrite($read->current());
$temp->flock(LOCK_UN);
}
// 重複チェック用のデータを追加する
$list[] = $line[0];
}
//一時ファイルをリネーム
rename("temp.csv", "list.csv");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment