CSV文件中的查找失败

时间:2016-03-31 21:24:24

标签: php csv

我有一个表单,用户输入他们的名字和姓氏。我想检查我的CSV文件中是否存在他们的全名,我用它来存储我表单的所有当前成员/用户。存储数据的格式为firstname,lastname。如果他们在场,我想打印出You are already a member

但是当我运行代码时,这不是我在输出中看到的。即使输入CSV文件中存在的名称,它也不会输出。

这是我的源代码:

$JLMembers = Array();

// Open the file of Members
if ($handle = fopen("JLMembers.csv", "r")) {
    // Get the next CSV line
    while ($data = fgetcsv($handle, 1000, ",")) {

        // Add that line to the array
        array_push($JLMembers, $data);
    }
}

foreach($JLMembers as $JLMember) {
    $FirstName = $_GET['FirstName'];
    $CurrentMemberFirstName = $JLMembers[0];

    if ($FirstName === $CurrentMemberFirstName) {

        foreach($JLMembers as $JLMember) {
            $SecondName = $_GET['LastName'];
            $CurrentMemberSecondName = $JLMembers[1];

            if ($SecondName === $CurrentMemberSecondName) {
                print "<br>You are already a member<br>";
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

当您使用$JLMembers[0]时,您正在使用$JLMember[0],其中包含CSV的第一行,其中包含foreach循环中当前行的第一列。而且你不需要两个循环,只需在一个循环中比较两列。

代码应为:

$FirstName = $_GET['FirstName'];
$LastName = $_GET['LastName'];
foreach ($JLMembers as $JLMember) {
    if ($FirstName == $JLMember[0] && $LastName == $JLMember[1]) {
        echo "<br>You are a member<br>";
        break; // Exit the loop once we found a match
    }
}