0

在棘手的情况下,我需要一些帮助。

目前我有一个看起来像这样的数组

Array
(
[0] => Array
    (
        [Task_ID] => 59
        [email] => m@m.com
    )

[1] => Array
    (
        [Task_ID] => 59
        [email] => m@m.com
    )

[2] => Array
    (
        [Task_ID] => 59
        [email] => z@z.com
    )

[3] => Array
    (
        [Task_ID] => 60
        [email] => m@m.com
    )

[4] => Array
    (
        [Task_ID] => 60
        [email] => z@z.com
    )

[5] => Array
    (
        [Task_ID] => 61
        [email] => z@z.com
    )

)

这是我当前的插入语句。

        if(is_array($myArr)){
        $valuesArr = array();
        foreach($myArr as $row){

            $sql = "INSERT INTO user_data (Task_ID, email, url) values ";
            $TaskID = (int) $row['Task_ID'];
            $email = mysql_real_escape_string( $row['email'] );

            $valuesArr[] = "('$TaskID', '$email')";
            $sql .= "('$TaskID', '$email')";
            mysql_query($sql) or exit(mysql_error());
        }
    }

我想做的是插入一个不在数组中的新值,即 URL 值。

对于 URL,我想为每封唯一的电子邮件增加一个数字,其中相同的电子邮件将获得相同的 URL 值。

SQL 语法应该是什么样子的示例。

INSERT INTO user_data (TaskID, email, url) values ('60', 'm@m.com','1')
INSERT INTO user_data (TaskID, email, url) values ('80', 'm@m.com','1')
INSERT INTO user_data (TaskID, email, url) values ('82', 'z@z.com','2')
INSERT INTO user_data (TaskID, email, url) values ('62', 'z@z.com','2')
INSERT INTO user_data (TaskID, email, url) values ('42', 'z@z.com','2')
INSERT INTO user_data (TaskID, email, url) values ('61', 'a@a.com','3')
INSERT INTO user_data (TaskID, email, url) values ('81', 'a@a.com','3')
INSERT INTO user_data (TaskID, email, url) values ('92', 't@t.com','4')
INSERT INTO user_data (TaskID, email, url) values ('32', 't@t.com','4')
INSERT INTO user_data (TaskID, email, url) values ('72', 't@t.com','4')

请注意,每更改一次电子邮件,URL 就会增加 1。请注意,TaskID 不是 PK 并且电子邮件不按顺序排列。

感谢您的阅读,非常感谢。

4

1 回答 1

1

试试看

if (is_array($myArr)) {
    $valuesArr = array();
    $addedEmails = array();

    $cnt = 0;
    foreach($myArr as $row){

        $sql = "INSERT INTO user_data (Task_ID, email, url) values ";
        $TaskID = (int) $row['Task_ID'];
        $email = mysql_real_escape_string( $row['email'] );

        if (!in_array($email, $addedEmails)) {
            $cnt++;
            $addedEmails[] = $email;
        }

        $valuesArr[] = "('$TaskID', '$email', '$cnt')";
        $sql .= "('$TaskID', '$email', '$cnt')";
        mysql_query($sql) or exit(mysql_error());
    }
}
于 2013-03-05T20:14:27.587 回答