在php数组中搜索相同的值

时间:2016-03-13 16:46:48

标签: php file-handling

我有一个链接到文本文件的数组,我需要用户输入输入的学生姓名和学号的信息。

if (isset ($_POST['stnum']) && isset ($_POST['stname'])) 
    {
        $studentNum = htmlentities ($_POST['stnum']);
        $studentName = htmlentities ($_POST['stname']);
        $DB = fopen ($students, 'r') or die ("$students cannot be opened for reading.");

        while ($record = fgets ($DB) and ! $foundNum and ! $foundName) 
        {
            $studentField = explode ("$$", htmlentities (trim ($record)));

            $foundNum = $studentNum === $studentField[0];
            $foundName = $studentName === $studentField[1];  
        }

        fclose ($DB);

        if ($foundNum && $foundName) 
        {
            echo $studentField[0], $studentField[1];
        }
    }

我无法弄清楚如何搜索具有相同名称但学生编号不同的学生。文件写得像这样

DA-708-3304$$Elizabeth Organ
GB-217-1214$$John Alexander
SE-412-2175$$Odell Thomas
SH-433-3012$$John Saunders
HU-737-1176$$Frederica Elias
DU-941-4244$$Nancy Sauceda
CC-671-5984$$Margaret Coppa
DA-220-7070$$Walter Snyder
HU-658-4475$$Elizabeth Organ
DU-255-9787$$John Saunders
CC-777-8752$$Hubert Green

例如,如果我尝试使用学生编号John Saunders搜索DU-255-9787,但它不起作用,John Saunders SH-433-3012会起作用,因为它首先显示在文件中。< / p>

1 个答案:

答案 0 :(得分:2)

为什么不在if条件下使用break?当条件满足时?

 while ($record = fgets ($DB) and ! $foundNum and ! $foundName) {
     $studentField = explode ("$$", htmlentities (trim ($record)));

     if (($studentName === $studentField[1]) &&  empty($studentNum))) {

          /* When only name is entered by user. So, the user whose number appears first in the list should be printed. */ 

         echo $studentField[1].", ".$studentField[0];
         break;

     } else if (($studentNum === $studentField[0]) &&  ($studentName === $studentField[1])) { 

        /* When both name and number is entered by user */

         echo $studentField[1].", ".$studentField[0];
         break;
      }


  }

希望这有帮助。

和平!的xD