0

我有一个 SELECT 查询,最多可以返回 1000 个名称 - 更有可能返回 300-400 个名称。

我想将输入字符串与 SELECT 查询返回的数组中的名称进行比较。

我有两个问题:

  1. for 循环需要多长时间才能遍历数组(所有 1000 个名称)以查找是否存在匹配值?和
  2. 有没有办法在找到匹配项后立即终止循环?(假设在第 10 个名称上找到匹配项,遍历其余名称将是一种浪费。是否有更多匹配项无关紧要 - 只需命中第一个就足以满足我的目的。)

我尝试过返回和退出,但两者都不完全按照我想要的方式工作。

这是我正在运行的代码来测试这个想法:第一个 php 文件包含名称数组

<?php 
$names=array("R","A","V");
$arrlengths=count($names);
?>

并包含在第二个文件中。

<?php
include 'test-2nd-include.php';
//the above file contains an array with three names
//it also contains the length of the array in the arrlengths variable


//in the test case we are using a name assigned to a variable in this file
//however, when used on the registration page, it will be a value that has come through   $_POST

$rr = "A";

 //a test variable that is initially = 0 but will be incremented if value is found in array

$ohno = 0;


for($xx=0;$xx<$arrlengths;$xx++)
{
echo "$ names [ $xx ] ", $names[$xx]; 
echo "<br>";


   if ($names[$xx] ==$rr) {
           // if the value is found then the test variable is set t
            $ohno = 1;
    }
}
if ($ohno > 0){
    echo " $rr already exists in our members list" ;
}
else {
echo "Congratulations! $rr is still available!" ;
}

?>

我所看到的是,如果我$ohno = 1;在最后的消息没有得到处理之后使用 return 或 exit。如果我将其if ($ohno > 0){......$rr is still available!" ;}移到 for 循环中,结果真的很奇怪!

我确定我错过了一些东西,但是在盯着它看了整个下午之后,我仍然找不到一种方法让代码在遇到第一个匹配项后停止运行并显示适当的消息——无论是在找到匹配项时还是在它找到匹配项时没有。

这就是第一个问题的原因!从长远来看,我花在这方面的时间是否值得节省服务器时间/处理?毕竟,对于最多 1000 个预期用户,这段代码可能会在一个月左右的时间内运行大约 300-400 次?!?

4

2 回答 2

3

要提前结束循环,请使用该break;语句。

但是,由于您显然是在尝试检查 SQL 表中是否已经存在名称,您可能应该直接向数据库询问信息:

select true from YourUserTable where name = 'theName' limit 1

然后检查返回的是 1 行还是 0 行。如果返回一行,则名称已存在;如果结果集为空,则名称仍然可用。这比首先从数据库中获取整个用户名列表然后手动检查要快得多。

如果您仍想迭代:

$found = false;
// Of course, a for loop is also possible
foreach ($namesArray as $position => $name) { 
    if ($name == $nameYouAreLookingFor) {
        $found = true;
        break;
    }
}
if ($found)
    echo "The name already exists";
else 
    echo "The name is still available";
于 2013-08-23T12:28:32.793 回答
-1

if ($names[$xx] ==$rr) { echo " $rr already exists in our members list" ; $ohno = 1;break;那么在循环之外有什么问题 if ($ohno == 0){ echo "Congratulations! $rr is still available!" ; }

时间的长短实际上取决于几个因素,我觉得这不是一个直截了当的答案。

于 2013-08-23T12:31:46.150 回答