我现在正在创建一个项目。我陷入了困境。我希望生成 8 位 PIN 码。如果该 PIN 码已存在于数据库中,则会生成另一个 PIN 码。计数 100 次后,如果总共 100 次生成的 PIN 码在数据库中,则生成 9 位 PIN 码。 我的代码如下:
$t=$this->generate_string(8);
$th= Booking::Where('token',$t)->first();
$count = 0 ;
if(isset($th)) {
if($count >= 100){
$t = $this->generate_string(9);
}else{
$t = $this->generate_string(8);
}
$count++;
}
$booking->token = $t;
和generate_string函数是
private function generate_string($length)
{
$character = '0123456789';
$character .= 'abcdefghijklmnopqrstuvwxyz';
$quantity_character = strlen($character);
$quantity_character--;
$Hash = NULL;
for ($x = 1; $x <= $length; $x++) {
$position = rand(0, $quantity_character);
$Hash .= substr($character, $position, 1);
}
return $Hash;
}
我的代码无法正常运行。请帮助我
最佳答案
您的代码不会增加计数器,因为您没有这样做。
我根据您的代码创建了一个示例,我使用递归来获取 token 。
生成代币函数:
private function generate_string($length)
{
$character = '0123456789';
$character .= 'abcdefghijklmnopqrstuvwxyz';
$quantity_character = strlen($character);
$quantity_character--;
$Hash = NULL;
for ($x = 1; $x <= $length; $x++) {
$position = rand(0, $quantity_character);
$Hash .= substr($character, $position, 1);
}
return $Hash;
}
检查 token 功能:
private function check_token($t){
return Booking::Where('token',$t)->first();
}
获取代币函数:
private function get_token($length, $count){
$t=$this->generate_string($length);
$r = check_token($t);
if(!isset($r)) // base case 1
return $t;
if($count <= 0) // base case 2
return $this->generate_string(9);
return $this->get_token($length, --$count); // decrements the $count and do recursion.
}
用法: ojit_代码
获取token函数使用递归生成token,递归如何停止?我们必须以基本情况为基础,
- 当
$token = $this->get_token(9, 5); //token length = 9, max tries = 5
表示不可能有 token 重复时。 - 当
!isset(check_token($t))
表示我们达到了最大可能尝试次数时。
如果没有任何一个基本情况匹配,该函数会再次调用 self 并递减 $count <= 0
。
检查并更新它以满足您的需求。
更新:
要在 token 与 $count
次数匹配的情况下获取 token ,请更新 n
函数,如下所示:
private function get_token($length, $count){
$t=generate_string($length);
$r = check_token($t);
if(isset($r)){ // token matches, then decrements $count
--$count;
}else{
return $t; // token did not matched, then return the token
}
if($count <= 0) // if we reaches the max tries, return token of length '$length + 1'
return $this->generate_string($length + 1);
return $this->get_token($length, $count);
}
关于php - 自动生成 token 在 php 中无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40701963/