我有一个工作更新,来自多个条目:
foreach(array_combine($_POST['eprof'] , $_POST['estudno']) as $prof => $sn){
mysqli_query($con,"UPDATE `table` SET `studno` = '$sn' WHERE `students`.`id` = '$prof'") or die(mysqli_error());
}
foreach(array_combine($_POST['eprof'] , $_POST['efn']) as $prof => $f){
mysqli_query($con,"UPDATE `table` SET `fn` = '$f' WHERE `students`.`id` = '$prof'") or die(mysqli_error());
}
foreach(array_combine($_POST['eprof'] , $_POST['emn']) as $prof => $m){
mysqli_query($con,"UPDATE `table` SET `mn` ='$m' WHERE `students`.`id` = '$prof'") or die(mysqli_error());
}
以上代码来自所选学生的一个或多个,具体取决于选中的复选框。有没有办法用更干净的foreach
来完成这项工作,例如将$sn
,$fn
,$m
合并为一个?
foreach(
array_combine(
$_POST['eprof'] ,
$_POST['estudno'],
$_POST['efn'],
$_POST['emn']
) as
$prof => $sn => $f => $m
){ "query here" }
这是正确的还是我做错了?
答案 0 :(得分:0)
假设它们具有相同的密钥:
foreach($_POST['eprof'] as $key => $prof){
$sn = $_POST['estudno'][$key];
$f = $_POST['efn'][$key];
$m = $_POST['emn'][$key];
mysqli_query($con, "UPDATE `table` SET `studno` = '$sn', `fn` = '$f', `mn` ='$m'
WHERE `students`.`id` = '$prof'");
}
如果没有相同的键控,那么你可以先在3个阵列上运行array_values()
来重新索引。