0

我只是无法找到解决这个问题的正确方法,我有两个数组。第一个数组 $attendance 具有以下键和值

Array
(
[attendance] => Array
    (
        [1] => 1
        [2] => 1
        [3] => 0
        [4] => 1
        [5] => 1
        [6] => 0
        [7] => 0
    )

这来自一个复选框,如果选中的值为 1,否则值为 0 第二个数组是 $remark

[remark] => Array
    (
        [1] =>
        [2] => 
        [3] =>  'sick'
        [4] => 
        [5] => 
        [6] =>  'leave'
        [7] =>  'On assignment'

    ) 

现在这就是键 1-7 所代表的意思,脚本用于员工出勤,键 1-7 是我数据库中员工表中的员工 ID。

现在我想要实现的是以这样的方式连接数组,看起来像这样

Array
(
[0] => Array
    (
        [employeeID] => 7
        [attendance] => 0
        [remark] => 'On assignment'
    )

[1] => Array
    (
        [employeeID] => 6
        [attendance] => 0
        [remark] => 'leave'
    )

[2] => Array
    (
        [employeeID] => 5
        [attendance] => 1
        [remark] => 
    )

//and so on
)

我正在使用 Codeigniter 如果我能够连接它,我也很想知道如何将多个数据插入到如下所示的员工表中,

employee's table
employeeID | date | status | remarks

我计划使用 CURDATE() 的日期,然后状态将再次保持出勤的 0 或 1 :备注和出勤数组中 1-7 的键是员工ID

更新!!这是我尝试过但没有奏效的方法。

$att = $_POST['attendance'];
$remarks = $_POST['remark'];

foreach($att as $employee_id=>$status)
        {
            $x=0;
            $employee[$x]['employee_id']=$employee_id;
            $employee[$x]['status']=$status;


            foreach($remarks as $employee_id=>$remark)
            {

                $employee[$x]['remark']=$remark;
                $x++;
            }
       }  
4

2 回答 2

1
$attendance = $_POST['attendance'];
$remarks = $_POST['remark'];

$collect = array();
foreach ($attendance as $employeeID => $attending) {
    $collect[] = array(
        "employeeID" => $employeeID,
        "attendance" => $attending,
        "remark" => isset($remarks[$employeeID]) ? $remarks[$employeeID] : ""
    );
}

$values = array();
foreach ($collect as $entry) {
    $values[] = "(" . ((int) $entry["employeeID"]) . ",
        CURDATE(),
        " . ((int) $entry["attendance"]) . ",
        '" . sql_escape($entry["remark"]) . "'
    )";
}
$query = "INSERT INTO `attendance`
    (`employeeID`, `date`, `status`, `remarks`)
    VALUES
    (" . implode(",", $values) . ")";

确保sql_escape用适当的转义函数替换。如果您使用的是 PDO,请使用它。

于 2013-08-23T09:29:26.263 回答
0

很简单,说实话……

$numOfEmployees = 8;

$concatArray = array();

foreach($attendance as $k => $v)
{
     $concatArray[] = array("employeeID" => $k, "attendance" => $v, "remark" => $remark[$k];
}

如果你的考勤表是 SQL 之类的,你可以使用foreach上面提到的 concatArray:

foreach($concatArray as $key => $value)
{
     $remark = $value['remark'];
     // sanitize remark for database
     $query = "INSERT INTO employees (ID, Date, Status, Remarks) VALUES ({$value['employeeID']}, NOW(), {$value['attendance']}, '{$value['remark']}');";
     // perform the actual query
}

请记住,这是一个非常普遍的例子,对数据库做了很多假设。

正如 Frits 所指出的,remark 字段应该被清理,也许通过使用mysqli_real_escape_stringMySQLi 或quotePDO - 取决于您使用的内容。

于 2013-08-23T09:19:09.623 回答