【问题标题】:Search for same value's in php array在php数组中搜索相同的值
【发布时间】:2016-03-13 16:46:47
【问题描述】:

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

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

例如,如果我尝试使用学生号 DU-255-9787 搜索 John Saunders,它不起作用,但 John Saunders SH-433-3012 可以,因为它首先出现在文件中。

【问题讨论】:

  • 不是答案,但在 while 块之前有重复行:“$studentField = explode ("$$", htmlentities (trim ($record)));"
  • 是的,我在发帖几分钟后就注意到了,不过还是谢谢你
  • 谷歌“返回所有相似的数组条目”...stackoverflow.com/questions/19966490/…
  • 我相信你在这里不需要htmlentities()

标签: php file-handling


【解决方案1】:

为什么不在 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

【讨论】:

  • 在循环中使用 break 语句为您的代码提供了很大的灵活性,因为您只想获得第一个搜索结果。
  • 这并不能回答他的问题……也不能解决他的问题。
  • 是的,确实如此。在你下结论之前,你可能想仔细看看,伙计。 :)
  • 是的,在您编辑了一大段代码之后?另外,如何将变量放在单引号内? '$studentField[0], $studentField[1]' 这不会输出任何数据。无论如何,你的答案被接受了,祝你的代码好运。
  • 关于单引号的好点,芽。谢谢!我现在已经编辑过了。不过,这是一个语法错误。更重要的是逻辑和优化。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 2011-05-20
相关资源
最近更新 更多