Last active
March 30, 2016 11:28
-
-
Save kurozumi/b4bc1005b3f367989f7f8eefd7629765 to your computer and use it in GitHub Desktop.
【PHP】CSVファイルの任意のカラムの重複したデータを削除する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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