php 重複 重複している文字列をなくすには、どうすればよいか?
php プログラミングにて重複をなくす方法です。
配列中の重複するデータを削除するための関数があります。
array_unique という関数です。
<?php
$array_before = array('one', 'two', 'three', 'one', 'two', 'three', 'four', 'five');
$array_after = array_unique($array_before);
foreach ($array_after as $data) {
print "$data\n";
}
?>
上記サンプルを実行すると、
one
two
three
four
five
と表示されます。
次にPHPのサンプルは、
実際にテキストファイルを読み込み、そして配列に格納する。
次に、関数array_uniqueを使って
重複をなくす。
最後に、別のテキストファイルに保存して
終了のプログラムのサンプルです。
<?php
//#############################
///////重複削除 del_overlap////
//#############################
/////////////////////////////////
////ファイル読込&配列格納////////
/////////////////////////////////
$array_before=file("tmp_keyword.txt");
/////////////////////////////////
///////重複の削除////////////////
/////////////////////////////////
$array_after = array_unique($array_before);
/////////////////////////////////
///////保存先ファイル指定し開く//
/////////////////////////////////
$fp = fopen("keyword_1.txt", "w+");
/////////////////////////////////
///////保存先ファイルへ書き込み//
/////////////////////////////////
foreach ($array_after as $data) {
fwrite($fp, "$data");
}
/////////////////////////////////
///////保存先ファイルを閉じる////
/////////////////////////////////
fclose($fp);
?>
上記サンプルにて、テキストファイル内の重複がなくなりました。
入力に使ったテキストファイルの例
---------------
one
one
one
two
two
---------------