笔记:updateBatch + bin2url + isJson
是那么无聊,偶尔也会写到一些不那么常用又那么常用的小功能。。。
/**
* 批量更新
*
* @param string $table 表名
* @param array $multipleData 要更新的数据
* @param string $id 条件字段
* @return bool
*/
public function updateBatch($table, array $multipleData = [], string $id = 'id')
{
if (!$multipleData) {
return false;
}
try {
$first = current($multipleData);
$updateColumn = array_keys($first);
$whereKey = !isset($first[$id]) ? 'id' : current($updateColumn);
unset($updateColumn[0]);
$updateSql = "UPDATE " . $table . " SET ";
$sets = [];
$bindings = [];
foreach ($updateColumn as $uColumn) {
$setSql = "`" . $uColumn . "` = CASE ";
foreach ($multipleData as $data) {
$setSql .= "WHEN `" . $whereKey . "` = ? THEN ? ";
$bindings[] = $data[$whereKey];
$bindings[] = $data[$uColumn];
}
$setSql .= "ELSE `" . $uColumn . "` END ";
$sets[] = $setSql;
}
$updateSql .= implode(', ', $sets);
$whereIn = collect($multipleData)->pluck($whereKey)->values()->all();
$bindings = array_merge($bindings, $whereIn);
$whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
$updateSql = rtrim($updateSql, ", ") . " WHERE `" . $whereKey . "` IN (" . $whereIn . ")";
// DB::enableQueryLog();
DB::update($updateSql, $bindings);
// $log = DB::getQueryLog();
// Log::info('queryLog:', $log);
return true;
} catch (\Exception $e) {
Log::info("update error:" . $e->getMessage());
return false;
}
}
/**
* 文件二进制数据
* 注意:一般传输的文件数据为base64编码过的二进制数据,需先解码处理
*
* @param $binFileData
* @return string
* @throws \Exception
*/
public function bin2url($binFileData)
{
$name = microtime(true) * 10000;
$tmpPath = storage_path($name);
file_put_contents($tmpPath, $binFileData);
$fileTypes = [255216 => 'jpg', 7173 => 'gif', 13780 => 'png'];
$fp = fopen($tmpPath, 'rb');
$bin = fread($fp, 2);
fclose($fp);
unlink($tmpPath);
$strInfo = unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
if (!isset($fileTypes[$typeCode])) {
throw new \Exception('文件格式有误,需传递jpg,gif,png格式');
}
$newPath = storage_path($name . '.' . $fileTypes[$typeCode]);
file_put_contents($newPath, $binFileData);
return $newPath;
}
/**
* json 判断
*
* @param $str
* @return bool
*/
if (!function_exists('isJson')) {
function isJson($str)
{
$arr = @json_decode($str, true);
if (is_null($arr) || !is_array($arr) || json_last_error() > 0) {
return false;
}
return true;
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接