2

考虑一个项目列表的 txt 文件

qqqqqq

啊啊啊

dddddd

哈哈哈

dddddd

哈哈哈

999999

并且列表中的某些项目是重复的。如何使用 php 输出一个文本文件,其中删除了任何重复的内容。

结果:

qqqqqq

啊啊啊

999999

4

2 回答 2

4

您可以使用array_unique

然后将内容返回

$file = fopen("filename.txt", "r");
$members = array();

while (!feof($file)) {
   $members[] = fgets($file);
}

fclose($file);
$unique_members = array(); 
$unique_members = array_unique($members);
var_dump($unique_members);
//write the content back to the file

上述解决方案仅用于删除重复项并使它们独一无二。感谢 nhahtdh 指出。

$count_members = array_count_values($members); 
foreach($count_members as $key=>$value)
{
   if($value == 1) 
       //write it to the file 
}

所以你不需要 array_unique 的东西 再次抱歉

于 2013-01-30T22:33:55.267 回答
1
<?php

$file = file_get_contents('file.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));

foreach ($row_array as $key=>$counts) {
    if ($counts==1)
        $no_duplicates[] = $key; 
}

//do what You want
echo '<pre>';
print_r($no_duplicates);

file_put_contents('no_duplicates.txt',$no_duplicates); //write to file. If file don't exist. Create it.
于 2013-01-30T22:40:49.580 回答