如何比较数据库中的两个数组并获得差异

时间:2013-09-17 06:11:59

标签: php mysql arrays

我在php中有关于数组的问题,任何人都可以帮助我如何比较数据库中的两个数组并获得它们的区别。差异将存储在数据库中。我是新的PHP和我很困惑处理数组函数。

我的代码如下:

这是我得到我的阵列的地方:

$year = $_POST['year'];
$course = $_POST['Course'];
$block = $_POST['block'];

$cheetah = mysql_query("SELECT stud_valid_nos FROM exam_students WHERE stud_subject_id = '$subject_id'")or die(mysql_error());  
while($validnos = mysql_fetch_array($cheetah)){
    $nos = $validnos['stud_valid_nos'];
    }
$tiger = mysql_query("SELECT sec_id_num FROM exam_sections WHERE sec_year = '$year' AND sec_course = '$course' AND sec_block = '$block'")or die(mysql_error()); 
while($idnum = mysql_fetch_array($tiger)){
    $id = $idnum['stud_valid_nos'];
    }

if($nos ???? $id){ ///this is where the arrays being compared.

inserts only the difference

}

else{

inserts the full array in the database
}

抱歉,我的英语不好:) Godbless!

我决定不再使用数组了,也许你们中有些人有一个piont,所以我重新组织我的代码,但它仍然无法正常工作。如何在我的数据库中添加学生编号而不重复?

这是我的新代码:

$cheetah = mysql_query("SELECT stud_valid_nos FROM exam_students WHERE stud_subject_id = '$subject_id'")or die(mysql_error());  
if(mysql_num_rows($cheetah)>0){

while($validnos = mysql_fetch_array($cheetah)){
    $nos = $validnos['stud_valid_nos'];

    $tiger = mysql_query("SELECT sec_id_num,sec_email FROM exam_sections WHERE sec_id_num <> '$nos' AND sec_year = '$year' AND sec_course = '$course' AND sec_block = '$block'")or die(mysql_error());
while($idnum = mysql_fetch_assoc($tiger)){
    $id = $idnum['sec_id_num'];
    $email = $idnum['sec_email'];


    $insert = mysql_query("INSERT INTO exam_students (stud_valid_nos, stud_email, stud_subject_id, stud_group_id ) VALUES ('$id','$email','$subject_id','$examinergroupid')")or die(mysql_error());
    $last = mysql_insert_id();
    $password = genRandomString();
    $rawr = mysql_query("INSERT INTO exam_passwords (pass_user_id,pass_password,pass_subject_id,pass_exam_id) VALUES ('$last','$password', '$subject_id', 0)")or die(mysql_error());

    }

    }

也许我应该在mysql_query中使用NOT IN或IS NULL函数?有谁可以告诉我如何摆脱我的问题?谢谢:))

3 个答案:

答案 0 :(得分:0)

$diff = array_diff($nos, $id);
if (count($diff)) {
     // insert diff
} else {
     // insert full array
}

http://php.net/manual/en/function.array-diff.php

答案 1 :(得分:0)

小心 - 想想你真正想要得到的东西:

看看这个例子:

$arr1 = array("a", "b", "c", "d");
$arr2 = array("c", "d", "e", "f");

$diff1 = array_diff($arr1, $arr2);
$diff2 = array_diff($arr2, $arr1);

$ diff1包含“a”和“b”,因为它将返回$ arr1中的内容,而不是$ arr2中的内容

$ diff2包含“e”和“f”,因为它将返回$ arr2中的内容而不是$ arr1中的内容

如果你想获得完全差异,你必须将$ diff1和$ diff2合并在一起:

$f_diff = array_merge($diff1, $diff2);

然后:

if (count($f_diff)) {
    //insert difference
}
else {
    //insert all
}

答案 2 :(得分:0)

只要结合这两个条件?:

INSERT INTO exam_sections
VALUES (SELECT * 
        FROM exam_sections
        WHERE sec_year = '$year' AND sec_course = '$course' AND sec_block = '$block'
        AND  stud_subject_id != '$subject_id'
        )

INSERT的列和值需要正确排列!