使用php检查文本文件/数组中的重复值 [英] check for duplicate value in text file/array with php
本文介绍了使用php检查文本文件/数组中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果有一个文件student.txt包含学生记录如下(首先,姓氏,学生ID),如:
If there is a file student.txt containing students record as following(first, last name, student ID) like:
John Smith 2320
Mary McHugh 4572
Sara Britny 2322
我想检查看看学生ID是否是唯一的。如果有重复的ID显示一个带有重复ID的错误消息。
I wanna check to see if the student ID is unique. if there are duplicated IDs display aan error message with the dupicated ID.
推荐答案
尝试这个:
$ids = array();
$users = fopen("ciccio.txt", "r"); //open file
while (!feof($users)) {
$line = fgets($users, 4096); //read one line
list ($firstname, $lastname, $id) = explode(" ", $line);
$id = (int)$id;
if (empty($ids)) {
$ids[] = $id;
} else {
if (in_array($id, $ids)) {
echo "Duplicate ID: " . $id . "<br/>";
} else {
$ids[] = $id;
}
}
}
fclose($users); #close file
这篇关于使用php检查文本文件/数组中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文