generateRandomNumber($length); $attempts++; if ($attempts > $maxAttempts) { throw new \Exception("无法生成唯一的用户编号,请重试"); } } while ($this->isUserIdExists($userId)); return $userId; } /** * 生成随机数字 * * @param int $length 数字长度 * @return string */ private function generateRandomNumber($length) { $min = pow(10, $length - 1); // 最小值,如 6 位是 100000 $max = pow(10, $length) - 1; // 最大值,如 6 位是 999999 return (string) mt_rand($min, $max); } /** * 检查用户编号是否已存在 * * @param string $userId * @return bool */ private function isUserIdExists($userId) { $userIds = \support\Db::table('hs_users')->pluck('user_sn')->toArray(); return in_array($userId, $userIds); } }