使用php检查文本文件/数组中的重复值

时间:2011-10-10 11:01:08

标签: php arrays duplicates

如果有一个文件student.txt包含学生记录如下(姓氏,姓氏,学生证),如:

   John Smith 2320
   Mary McHugh 4572
   Sara Britny 2322

我想检查学生证是否独一无二。如果有重复的ID,则显示带有重复ID的错误消息。

5 个答案:

答案 0 :(得分:1)

arrayWithId = array
FOR EACH record AS rec IN file
   IF arrayWithId NOT CONTAINS rec THEN
      ADD rec TO arrayWithId
   ELSE
      display error
END FOR
# if you get here without any errors displayed there are no duplicates

答案 1 :(得分:0)

只需逐行读取文件并保存所有ID。如果已经保存了一个id,则抛出错误。

$line = /* ... */
$data = explode( ", ", $line );

// should contain the id
$id = $data[2];

答案 2 :(得分:0)

<?php
$file = "student.txt";
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);

$list = array();

$list = explode("\n",$contents);
$list = array_map("trim", $list);

$current = "foo@bar.com";

echo in_array($current,$list) ? $current.' exists' : $current.' does not exist';
?>

答案 3 :(得分:0)

迭代输入数组,获取每个项目的ID,如果ID是新的,则存储ID,如果不是,则给出错误:

$filename = 'students.txt';

$array = file($filename, FILE_IGNORE_NEW_LINES);

$unique = array();
foreach($array as $line => $student)
{
    $r = preg_match('/ (\d+)$/', $student, $matches);
    if (!$r) continue;
    list(,$id) = $matches;
    if (isset($unique[$id]))
        printf("Duplicate ID found (%d) in '%s' line %d.\n", $id, $student, $line);
    else
        $unique[$id] = 1;
}

答案 4 :(得分:0)

试试这个:

$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