$arr=[ 'id'=>[
1,
2
], 'temp'=>[ 'x','y'
], 'user'=>[ 'b','f'
]
];
這樣的數(shù)組如何生成兩條update的sql語句
update set temp=x ,user=b where id=1
update set temp=y,user=f where id=2
1 回答

皈依舞
TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
<?php$arr=[ 'id'=>[ 1, 2 ], 'temp'=>[ 'x','y' ], 'user'=>[ 'b','f' ] ]; $sqls = []; $whereKey = key($arr); $whereParams = array_shift($arr); $updateKeys = array_keys($arr);foreach ($whereParams as $index => $whereValue) { $updateSqlArr = array_map(function($updateKey) use ($index, $arr) { return $updateKey . ' = ' . $arr[$updateKey][$index]; }, $updateKeys); $sqls[] = 'update tablename set ' . implode(', ', $updateSqlArr) . ' where ' . $whereKey . ' = ' . $whereValue; } var_dump($sqls);
結(jié)果
array(2) { [0]=> string(52) "update tablename set temp = x, user = b where id = 1" [1]=> string(52) "update tablename set temp = y, user = f where id = 2"}
如果使用 ORM 框架更新數(shù)據(jù)例如Article::where($whereKey, $whereValue)->update($updateArr);
,可以改為
<?php$arr=[ 'id'=>[ 1, 2 ], 'temp'=>[ 'x','y' ], 'user'=>[ 'b','f' ] ];// 數(shù)組第一個(gè)元素是 where 條件, 其余的所有元素都是更新對(duì)象$whereKey = key($arr);// 獲取 where 條件并從數(shù)組去掉$whereParams = array_shift($arr); $updateKeys = array_keys($arr);foreach ($whereParams as $index => $whereValue) { $updateArr = []; foreach ($updateKeys as $updateKey) { $updateArr[$updateKey] = $arr[$updateKey][$index]; }
- 1 回答
- 0 關(guān)注
- 488 瀏覽
添加回答
舉報(bào)
0/150
提交
取消