我已经编写了一个脚本,用于检查通过textarea接收到的名称的批量输入,并省略已经在数据库中的所有值。如果你只输入一个重复的名字,它会起作用。如果输入两个或更多,它将过滤出第一个重复名称,将其余的名称视为唯一名称并将其插入数据库。我无法弄清楚为什么。首先,这是一个内置于脚本另一部分的数组。它是从数据库查询生成的:PHP的foreach循环弄乱了我的in_array函数
Array
(
[0] => john
[1] => peter
[2] => max
[3] => jake
)
此数组被称为$ onlyHandles。然后这是脚本:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles);
if(count($handles)>200){
echo 'error';
exit(1);
}
foreach($handles as $handle) {
$handleRep = strtolower(str_replace('@','',$handle));
$handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
if ($count > 0) {
echo 'error';
exit(1);
}
else{
if (in_array($handleClean, $onlyHandles)){
$delmessage .= "<p>".$handleClean." is already in your list.</p>";
}
else{
$sqlIns = "INSERT INTO...blah blah blah)";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
}
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to list succesfully!</p>" ;
}
}
现在,如果在textarea中输入“john”,它会喊出名称已经存在。如果输入“john”和“max”,它将省略john并添加最大值。
任何帮助将不胜感激。
P.S.关于查询格式,我知道,我知道,谢谢!
您好!我认为你必须修改你的'$ handle'变量,因为它可能在它周围有一些空格... 然后关于你的问题,我不理解它。你的代码看起来是“干净的”,也许你应该考虑将strict标志设置为true [见函数定义](https://secure.php.net/in_array)。 – shulard
当然,您可以使用数组交集函数和多插入来实现更高效的过程。它将允许节省处理时间并简化此代码。 – shulard
看一看[array_diff](https://secure.php.net/manual/en/function.array-diff.php)! – shulard