我只是无法正确解决这个问题,我有两个数组。 第一个数组$ 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是我数据库中employee表中的employeeID。
现在我想要实现的是以这样的方式连接数组
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的密钥都是employeeID
更新!! 这是我试过但没有用的。
$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++;
}
}
答案 0 :(得分: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那么。
答案 1 :(得分:0)
很简单,说实话......
$numOfEmployees = 8;
$concatArray = array();
foreach($attendance as $k => $v)
{
$concatArray[] = array("employeeID" => $k, "attendance" => $v, "remark" => $remark[$k];
}
如果您的考勤表与SQL类似,您可以在上面提到的concatArray中使用foreach
进行处理:
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所说,应该对备注字段进行消毒,可能是对MySQLi使用mysqli_real_escape_string
或对PDO使用quote
- 取决于您使用的是什么。