PHP 短 ID 生成
public static function generate(): string
{
$a = 53; // 乘数,满足Hull - Dobell条件
$c = 3; // 加数,与模数互质
$m = 26 ** 6; // 模数,26^6
$microtime = microtime(true);
$microtime = str_replace('.', '', $microtime);
$randomNumber = random_int(100, 999);
$seed = $microtime.$randomNumber; // 使用时间戳随机数作为种子
$current = $seed % $m;
$code = '';
$num = $current;
for ($j = 0; $j < 6; $j++) {
$remainder = $num % 26;
$code = chr(97 + $remainder).$code; // 转换为a - z
$num = (int) ($num / 26);
}
// 计算下一个LCG值,为下一次调用做准备(如果需要)
$current = ($a * $current + $c) % $m;
return $code;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: