Recently, due to some reasons at my current company, I have to get back into the job hunt. During the interview process, I also encountered some interesting interview questions. Maybe I didn't think about it at the time, but I thought about it again after I came back. Question 1: Given a user's ID (the ID is a long integer), generate a unique invitation code for the user based on the user ID (invitation code range ([a-z0-9])? Code implementation!
Several things I was thinking about at the time The solutions are relatively simple:
<?php function createCode($userId) { //方案一: $currentTime = time(); $code = "{$userId}{$currentTime}"; return $code; //方案二: while(true){ //获取一个随机字符串 $code = getRandString(8); //判断该字符串是否存在 if( ! checkExists($code)) return $code; } }
The several solutions that came to mind at the time were almost all evolved from these two solutions
Disadvantages of the two solutions:
Option 1: The string length is too long and the invitation code is average. They all need to be passed between users. Too long is not conducive to users’ memory.
Option 2: Every time you generate a random string, you need to check whether it already exists in the database. When it is large, it will inevitably affect efficiency. For developers who pursue efficiency, this solution is not the best!
New solution:
The characters a-z0-9 can be considered directly. How about converting the user ID into a hexadecimal number?
Code implementation:
<?php function createCode($userId) { static $sourceString = [ 0,1,2,3,4,5,6,7,8,9,10, 'a','b','c','d','e','f', 'g','h','i','j','k','l', 'm','n','o','p','q','r', 's','t','u','v','w','x', 'y','z' ]; $num = $userId; $code = ''; while($num) { $mod = $num % 36; $num = (int)($num / 36); $code = "{$sourceString[$mod]}{$code}"; } //判断code的长度 if( empty($code[4])) str_pad($code,5,'0',STR_PAD_LEFT); return $code; }
Compared with the first two solutions, this newer solution makes up for the shortcomings of the first two solutions while ensuring that the same user generates invitation codes repeatedly. The advantages remain unchanged. Of course, this implementation method needs to be treated differently based on specific needs
The above introduces the method of generating user invitation codes, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.