0

嗨朋友们,我需要跳过foreach中的重复条目,而不是继续其余的条目,请告诉我该怎么做

foreach($arr as $key=>$arr1)
{
    echo "<pre>";

$insert=mysql_query("INSERT INTO auth_user(id,username,first_name,last_name,email,password,is_active,date_joined) VALUES('".$key."','".$arr1['username']."','".$arr1['firstname']."','".$arr1['lastname']."','".$arr1['email']."','NULL','".$arr1['is_active']."','".$arr1['date_joined']."')",$conn1);

echo $insert .'<br/>';
if($insert)
    {
        echo "DATA MIGRATE FOR USER ".$key;
        $insert1=mysql_query("INSERT INTO stylequiz_score(user_id,style_quiz_score,style_quiz_answer) VALUES('".$key."','".$arr1['style_quiz_score']."','".$arr1['style_quiz_answer']."')",$conn1);
    }
    else
    {
       echo  ("Error In MIGRATION FOR USER ".$key . mysql_error());

    }
}
4

3 回答 3

2

使用 INSERT 语句的 IGNORE 修饰符:

$insert1=mysql_query("INSERT IGNORE INTO stylequiz_score(user_id,style_quiz_score,style_quiz_answer) VALUES('".$key."','".$arr1['style_quiz_score']."','".$arr1['style_quiz_answer']."')",$conn1);

如果正在插入的行会出现重复键错误,则此修饰符会导致插入被跳过而没有错误。

于 2013-02-01T05:32:38.010 回答
1

array_unique 将删除数组中的所有重复值。在你的情况下,试试这样。

$arr = array_unique($arr);

你不需要做任何额外的功能。

于 2013-02-01T05:20:38.460 回答
0

假设您在$arr

采用array_unique

$res_array = array_unique($arr);

参考: http: //php.net/manual/en/function.array-unique.php

要检查数据库中的重复项,请将插入查询置于 if 条件中

$sql   = mysql_query("SELECT * FROM auth_user WHERE email = '".$arr1['email']."'");
if(mysql_numrows($sql) == 0){
   $insert=mysql_query("INSERT INTO auth_user(id,username,first_name,last_name,email,password,is_active,date_joined) VALUES('".$key."','".$arr1['username']."','".$arr1['firstname']."','".$arr1['lastname']."','".$arr1['email']."','NULL','".$arr1['is_active']."','".$arr1['date_joined']."')",$conn1);
}
else{
   $insert = false;
}
于 2013-02-01T05:19:22.207 回答