所以我有这个我想排序的文本文件。文本文件的内容如下所示:当我写它们时,我在每行的末尾使用了"''r'"
基尔是我用来写的代码:
$name = $_POST['name'];
$email = $_POST['email'];
$fileName = "GuestBook.txt";
$fh = fopen($fileName, "a");
fwrite($fh, $name);
fwrite($fh, "----");
fwrite($fh, $email . "'r'n");
fclose($fh);
在记事本上打开txt文件,它看起来像这样:
aaa----aaa
ggg----ggg
sss----sss
www----www
ttt----ttt
ppp----ppp
ggg----ggg
zzz----zzz
www----www
现在我希望它显示它排序并删除重复项:
aaa----aaa
ggg----ggg
ppp----ppp
sss----sss
ttt----ttt
www----www
zzz----zzz
这是我为对它们进行排序所做的:
$fileName = "GuestBook.txt";
$data = file_get_contents($fileName);
$split = explode("'n",$data);
sort($split);
$data = implode("'n",$split);
file_put_contents($fileName, $data);
这就是我删除重复项的功能
$fileName = "GuestBook.txt";
$lines = file($fileName);
$lines = array_unique($lines);
file_put_contents($fileName, implode("'n",$lines));
要从文件中获取排序和唯一的输出,您可以执行以下操作:
首先将文件读入一个带有 file()
的数组,这样你就把每一行作为一个数组元素。然后您可以使用array_unique()
,这样您只有唯一的线条/元素。
之后,您可以使用usort()
对数组进行排序,并将strcasecmp
作为回调应用。
法典:
<?php
$fileName = "GuestBook.txt";
$lines = file($fileName, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = array_unique($lines);
usort($lines, "strcasecmp");
print_r($lines);
?>
如果你想存储它们已经是唯一的,你可以这样做:
还可以使用 file()
将文件读入数组中,只需与in_array()
检查数组中是否已经有该值。如果没有,则将值添加到带有 file_put_contents()
的文件中。
法典:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$fileName = "GuestBook.txt";
$lines = file($fileName, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if(!in_array($name . "----" . $email, $lines)){
file_put_contents($fileName, $name . "----" . $email . "'r'n", FILE_APPEND);
}
?>
如果要将已排序的值添加到文件中,可以这样做:
再次将文件放入数组中,将值添加到数组中,对其进行排序,然后可以将其放回原处。
法典:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$fileName = "GuestBook.txt";
$lines = file($fileName, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines[] = $name . "----" . $email;
usort($lines, "strcasecmp");
file_put_contents($fileName, implode("'r'n", $lines), FILE_APPEND);
?>
当然,如果您希望它们已经唯一且已排序,只需将上面的两个代码片段组合在一起即可。
将文件加载到数组中,删除重复项,然后排序:
$lines = array_unique(file('/path/to/file.txt'));
sort($lines);
根据文件结构,您可以使用FILE_IGNORE_NEW_LINES
和FILE_SKIP_EMPTY_LINES
中的一个或两个。
然后保存,如果您不使用FILE_IGNORE_NEW_LINES
(如果是这样,您必须添加它们):
file_put_contents('/path/to/file.txt', $lines);
<?php
$fh = fopen('file.txt', 'r');
$lines = array();
while ( $line = fgets($fh) ) {
$lines[] = $line;
}
$arr = array_unique($lines);
foreach ( $arr as $line ) {
echo $line . "'r'n";
}