和php数组如下所示
$assign=array("sFirst"=>array("101","102","103"),"sSecond"=>array("104","105"),"sThird"=>array("106"));
我的问题 我想将上表的状态列更新为1,将supervisor列更新为reg_id值所在的数组的键 存在于数组中,以便表格看起来像这样 决赛桌看
我的尝试 我只知道如何在单个数组中完成,而不是在多数组数组中 如下图所示
$sql2="update stack set status=1,supervisor='sFirst'
where reg_id in (" . implode(",", $assign['sFirst']) . ")";
答案 0 :(得分:0)
你在找这个吗?
foreach ($assign as $key => $value)
{
$sql2="update stack set status=1,supervisor=$key
where reg_id in (" . implode(",", $value) . ")";
//execute query here
}
编辑: 在不知道另一个解决方案的情况下,如果您只想进行单个查询。 您可以创建一个循环来生成查询。 有点像这个
$case="case "
$in=""
foreach ($assign as $key => $value)
{
$imploded=implode(",", $value);
$case=$case . " when reg_id in (" . $imploded . ") then " .$key ;
$in= in . $imploded;
$sql2="update stack set status=1,supervisor=" . $case . " end
where reg_id in (" . $in . ")";
}
你需要考虑逗号,因为我没有注意。
答案 1 :(得分:0)
如果你真的想避免在for循环中执行查询, 以下代码将提供单个更新查询,该查询将按预期更新记录
<?php
$assign=array("sFirst"=>array("101","102","103"),"sSecond"=>array("104","105"),"sThird"=>array("106"));
$supervisorUpdate = "( CASE ";
$whereArr = array();
foreach($assign as $key=>$value){
$supervisorUpdate .= " WHEN reg_id IN (" . implode(",", $value) . ") THEN '$key' ";
$whereArr[] = implode(",", $value);
}
$where = " WHERE reg_id IN (" . implode(",", $whereArr) . ") " ;
$supervisorUpdate .= " ELSE supervisor END )" ;
$sql = "update stack set status=1, supervisor = " . $supervisorUpdate . $where;
如果你在$ sql之上回显,那么它将为你提供如下更新查询:
update stack
set
status=1,
supervisor = ( CASE
WHEN reg_id IN (101,102,103) THEN 'sFirst'
WHEN reg_id IN (104,105) THEN 'sSecond'
WHEN reg_id IN (106) THEN 'sThird'
ELSE supervisor END )
WHERE reg_id IN (101,102,103,104,105,106)