Thinkphp怎么批量更新数据
2个回答
展开全部
thinkphp批量更新数据可以参考如下三种方法:
方法一:
//批量修改 data二维数组 field关键字段 参考ci 批量修改函数 传参方式
function batch_update($table_name='',$data=array(),$field=''){
if(!$table_name||!$data||!$field){
return false;
}else{
$sql='UPDATE '.$table_name;
}
$con=array();
$con_sql=array();
$fields=array();
foreach ($data as $key => $value) {
$x=0;
foreach ($value as $k => $v) {
if($k!=$field&&!$con[$x]&&$x==0){
$con[$x]=" set {$k} = (CASE {$field} ";
}elseif($k!=$field&&!$con[$x]&&$x>0){
$con[$x]=" {$k} = (CASE {$field} ";
}
if($k!=$field){
$temp=$value[$field];
$con_sql[$x].= " WHEN '{$temp}' THEN '{$v}' ";
$x++;
}
}
$temp=$value[$field];
if(!in_array($temp,$fields)){
$fields[]=$temp;
}
}
$num=count($con)-1;
foreach ($con as $key => $value) {
foreach ($con_sql as $k => $v) {
if($k==$key&&$key<$num){
$sql.=$value.$v.' end),';
}elseif($k==$key&&$key==$num){
$sql.=$value.$v.' end)';
}
}
}
$str=implode(',',$fields);
$sql.=" where {$field} in({$str})";
$res=M($table_name)->execute($sql);
return $res;
}
//测试
function test(){
$update_array=array();
for ($i=2; $i <7 ; $i++) {
$data=array();
$data['id']=$i;
$data['memeber_type']=2;
$data['memeber_type_state']=1;
$update_array[]=$data;
}
$res=$this->batch_update('yl_member',$update_array,id);
var_dump($res);
}
方法一:
//批量修改 data二维数组 field关键字段 参考ci 批量修改函数 传参方式
function batch_update($table_name='',$data=array(),$field=''){
if(!$table_name||!$data||!$field){
return false;
}else{
$sql='UPDATE '.$table_name;
}
$con=array();
$con_sql=array();
$fields=array();
foreach ($data as $key => $value) {
$x=0;
foreach ($value as $k => $v) {
if($k!=$field&&!$con[$x]&&$x==0){
$con[$x]=" set {$k} = (CASE {$field} ";
}elseif($k!=$field&&!$con[$x]&&$x>0){
$con[$x]=" {$k} = (CASE {$field} ";
}
if($k!=$field){
$temp=$value[$field];
$con_sql[$x].= " WHEN '{$temp}' THEN '{$v}' ";
$x++;
}
}
$temp=$value[$field];
if(!in_array($temp,$fields)){
$fields[]=$temp;
}
}
$num=count($con)-1;
foreach ($con as $key => $value) {
foreach ($con_sql as $k => $v) {
if($k==$key&&$key<$num){
$sql.=$value.$v.' end),';
}elseif($k==$key&&$key==$num){
$sql.=$value.$v.' end)';
}
}
}
$str=implode(',',$fields);
$sql.=" where {$field} in({$str})";
$res=M($table_name)->execute($sql);
return $res;
}
//测试
function test(){
$update_array=array();
for ($i=2; $i <7 ; $i++) {
$data=array();
$data['id']=$i;
$data['memeber_type']=2;
$data['memeber_type_state']=1;
$update_array[]=$data;
}
$res=$this->batch_update('yl_member',$update_array,id);
var_dump($res);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询