【问题标题】:php alphanumeric id with fixed letter position具有固定字母位置的php字母数字ID
【发布时间】:2016-10-20 20:03:00
【问题描述】:

我需要在 PHP 中创建唯一的字母数字 ID,长度为 6 个字符。

虽然我找到了很多解决这个问题的答案,但我希望将字母定位在 ID 中的特定位置,例如 A1B2C3(第一个、第三个和第五个字符)。

对此我唯一的解决方案是创建 6 个“for”循环(a-z 和 0-9 * 3 次)并将输出插入到数组中,然后插入到 MySQL 表中。肯定不会重复,但是有没有更好的办法?

到目前为止我的代码是:

<?php

   $id=array();

   for($a='A';$a!='AA';$a++){
        for($b=1;$b<=9;$b++){
           for($c='A';$c!='AA';$c++){
              for($d=1;$d<=9;$d++){
                  for($e='A';$e!='AA';$e++){
                     for($f=1;$f<=9;$f++){

                       $id[]=$a.$b.$c.$d.$e.$f;
                     }
                  } 
              }
           }
        }
    }

    foreach ($id as $value) {
        echo "$value \n";
    }
?> 

【问题讨论】:

  • 请包含示例数据、您迄今为止尝试过的代码以及您想要的结果的虚拟输出。
  • unique 与什么相比,数据库?随机解决方案,eval.in/591689,虽然不是唯一的..
  • 用我的代码更新了我的问题。从我的代码创建的结果开始,数据库开始为空,如此独特。使用上面的代码,我没有重复,但这是创建我的 id 的好方法吗?
  • 一次要创建多少个ID?您的代码创建了很多 ID。
  • @bloodyKnuckles 起初我想要 20.000 个 ID,但是当使用这 20.000 个时,我想从我停止的 ID+1 继续。所以我正在考虑也许我应该首先更改最后 4 位数字并保持前 2 位不变。需要时继续第二个和第一个。

标签: php mysql alphanumeric unique-id


【解决方案1】:

如果您需要顺序 ID:

// to start
//$numIds = 20000;
//$id = '';

// to add more
$numIds = 1000;
$id = 'A1J5M2'; // put MAX id from DB here

if ( '' !== $id ) { // increment id
  list($aa, $bb, $cc, $dd, $ee, $ff) = str_split($id);
  $arr = [$aa, $bb, $cc, $dd, $ee, $ff];
  list($aa, $bb, $cc, $dd, $ee, $ff) = incc($arr, count($arr) - 1);
}
else {
  list($aa, $bb, $cc, $dd, $ee, $ff) = ['A',1,'A',1,'A',1];
}

// generate ids    
$ids = [];

for($a=$aa;$a!='AA';$a++){
  for($b=$bb;$b<=9;$b++){
    $bb = 1; // reseting b - f is necessary when adding more ids
    for($c=$cc;$c!='AA';$c++){
      $cc = 'A';
      for($d=$dd;$d<=9;$d++){
        $dd = 1;
        for($e=$ee;$e!='AA';$e++){
          $ee = 'A';
          for($f=$ff;$f<=9;$f++){
            $ff = 1;

            $ids[] = "$a$b$c$d$e$f";
            // break out of all loops when desired number is reached
            if ( $numIds <= count($ids) ) { break 6; }
}}}}}}

// db setup
$conn = mysqli_connect('localhost', 'root', '', 'dbtest');
$insertstmt = mysqli_prepare($conn, 'INSERT INTO ids (id) VALUES (?)');

// insert ids
mysqli_stmt_bind_param($insertstmt, 's', $id);    
mysqli_autocommit($conn, false);
foreach ( $ids as $id ) {
  mysqli_stmt_execute($insertstmt);
}
mysqli_commit($conn);
mysqli_close($conn);


// function to increment given id, accommodates rolling over, e.g., A9 -> B1
function incc ($arr, $idx) {
  if ( is_int(intval($arr[$idx])) ) {
    if ( 9 == $arr[$idx] ) {
      $arr[$idx] = 1;
      $arr = incc($arr, --$idx); // recursing
    }
    else {
      $arr[$idx]++;
    }
  }
  else {
    if ( 'Z' === $arr[$idx] ) {
      $arr[$idx] = 'A';
      $arr = incc($arr, --$idx);
    }
    else {
      $ord = ord($arr[$idx]);
      $ord++;
      $arr[$idx] = chr($ord);
    }
  }
  return $arr;
}

PHP Sandbox demo

【讨论】:

  • 非常感谢您的有用回答。问题解决了。再次感谢
【解决方案2】:

对于唯一和随机 ID,当您不需要顺序 ID 时:

$numIds = 20000; // how many ids do you want to generate and insert?

// db setup
$conn = mysqli_connect('localhost', 'root', '', 'dbtest');
$insertstmt = mysqli_prepare($conn, 'INSERT INTO ids (id) VALUES (?)');

// generate ids array
$ids = [];
for ($ii = 0; $ii < $numIds; $ii++) {
  do { // execute loop at least once

    // inspired by @chris85 's comment
    $id = randChr() . rand(0, 9) . randChr() . rand(0, 9) . randChr() . rand(0, 9);

  } while ( // try again if found in either db or array
    idInDb($conn, $id) || // not actually needed on first run
    (0 < count($ids) && in_array($id, $ids, true))
  );
  $ids[] = $id; // is unique, add to array
}

// insert ids
mysqli_stmt_bind_param($insertstmt, 's', $id);    
mysqli_autocommit($conn, false);
foreach ( $ids as $id ) {
  mysqli_stmt_execute($insertstmt);
}
mysqli_commit($conn);
mysqli_close($conn);


// helper functions

function randChr () { // generate random alpha character
  return chr(rand(65, 90)); // upper case only
  //return chr(rand(0, 1) ? rand(65, 90) : rand(97, 122));
  // use alternative return for upper AND lower case
}

function idInDB ($conn, $testid) { // check for id in db
  $query = "SELECT id FROM ids WHERE id = '$testid'";
  $result = mysqli_query($conn, $query);
  $found = 0 < mysqli_num_rows($result);
  mysqli_free_result($result);
  return $found;
}

PHP Sandbox demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2016-04-02
    • 2018-04-22
    相关资源
    最近更新 更多