繁体   English   中英

如何生成唯一的6位数代码

[英]How to generate unique 6 digit code

我想生成6位数的唯一代码,但我希望前3个是字母表,最后3个是数字,如下例所示。

AAA111
ABD156
DFG589
ERF542...

请帮助创建具有以上组合的代码..

下面是我的代码..

public function generateRandomString()  {
        $characters = '1234567890';
        $length = 6;
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

你想要前3个字符作为字母,最后3个字符作为数字? 然后你应该彻底处理它们。

function genRandStr(){
  $a = $b = '';

  for($i = 0; $i < 3; $i++){
    $a .= chr(mt_rand(65, 90)); // see the ascii table why 65 to 90.    
    $b .= mt_rand(0, 9);
  }

  return $a . $b;
}

您还可以使用函数参数来添加动态性,对于随机顺序,您可以执行以下操作:

// PHP >= 7 code
function genRandStr(int $length = 6, string $prefix = '', string $suffix = ''){
  for($i = 0; $i < $length; $i++){
    $prefix .= random_int(0,1) ? chr(random_int(65, 90)) : random_int(0, 9);
  }

  return $prefix . $suffix;
}

对PHP版本<7使用mt_rand() ,否则建议使用random_int()

您仍然需要检查可能的冲突并将其置于while循环中。

function generateRandomString()  {
    $letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $digits = '1234567890';
    $randomString = '';
    for ($i = 0; $i < 3; $i++) {
        $randomString .= $letters[rand(0, strlen($letters) - 1)];
    }
    for ($i = 0; $i < 3; $i++) {
        $randomString .= $digits[rand(0, strlen($digits) - 1)];
    }
    return $randomString;
}

http://sandbox.onlinephpfunctions.com/code/ec0b494c4e08ab220fe7601504c8611459690c33

请检查以下代码:

<?php
    $string1 = str_shuffle('abcdefghijklmnopqrstuvwxyz');
    $random1 = substr($string1,0,3);
    $string2 = str_shuffle('1234567890');
    $random2 = substr($string2,0,3);

    echo $random = $random1.$random2;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM