皈依舞
<?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);结果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 框架更新数据例如Article::where($whereKey, $whereValue)->update($updateArr);,可以改为<?php$arr=[ 'id'=>[ 1, 2
], 'temp'=>[ 'x','y'
], 'user'=>[ 'b','f'
]
];// 数组第一个元素是 where 条件, 其余的所有元素都是更新对象$whereKey = key($arr);// 获取 where 条件并从数组去掉$whereParams = array_shift($arr);
$updateKeys = array_keys($arr);foreach ($whereParams as $index => $whereValue) {
$updateArr = []; foreach ($updateKeys as $updateKey) {
$updateArr[$updateKey] = $arr[$updateKey][$index];
}