3

我需要从这封信中生成代码

$a = array(
    'B','C','D','F','G','H','J','K','L','M','N','O',
    'P','Q','R','S','T','V','W','X','Y','Z','1','2',
    '3','4','5','6','7','8','9','0'
);

但是有两个条件:每个代码必须是唯一的,并且包含 10 个字母。我不想随机,因为效率低下。相反,我想要每个字母,例如:

  1. BBBBBBBBBB
  2. BBBBBBBBBC
  3. BBBBBBBBBD

等等..有什么想法吗?

4

4 回答 4

4

我认为你真正想要的是一个序列号列表(因此根本不是随机的),它有一个非常规的基本系统。如此BBBBBBBBB0虽然BBBBBBBC如此1。这并不难做到,但显然你必须自己编写代码。像这样的东西可能会起作用:

function generate($num) {
    $num = base_convert($num, 10, 32); // convert the number to base 32
    $num = str_pad($num, 10, "0", STR_PAD_LEFT); // pad it with zeros to the left
    $num = str_replace(array(
        '0','1','2','3','4','5','6','7','8','9','a','b',
        'c','d','e','f','g','h','i','j','k','l','m','n',
        'o','p','q','r','s','t','u','v'
    ), array(
        'B','C','D','F','G','H','J','K','L','M','N','O',
        'P','Q','R','S','T','V','W','X','Y','Z','1','2',
        '3','4','5','6','7','8','9','0'
    ), $num); // replace the normal characters with your custom array

    echo $num, "\n";
}

for ($i = 0; $i < 10; $i++) generate($i);

显然,您可以10将语句中的 in更改为for您喜欢的任何内容,然后插入数据库而不是echoing。显然,生成 160 万条记录需要一些时间。

上面的代码给出了以下输出:

BBBBBBBBBB
BBBBBBBBBC
BBBBBBBBBD
BBBBBBBBBF
BBBBBBBBBG
BBBBBBBBBH
BBBBBBBBBJ
BBBBBBBBBK
BBBBBBBBBL
BBBBBBBBBM
于 2012-08-24T08:49:30.810 回答
3
<?php

$length = 3;

$letters = str_split("ABC"); // define your dictionary here

$index = array_fill(0, $length, 0);

$key = $length - 1;
while(true) {   
    $code = "";
    for($i=0;$i<$length;$i++) {     
        $code .= $letters[$index[$i]];      
    }
    echo $code ."<br/>"; // output code

    $index[$key]++;

    while(!isset($letters[$index[$key]])) {
        $index[$key] = 0;
        $key--;
        if($key < 0) {
            break 2;
        }       
        $index[$key]++;
    }   
    $key = $length - 1; 
}

例子:

于 2012-08-24T08:44:01.583 回答
1
<?php

$a = array(
    'B','C','D','F','G','H','J','K','L','M','N','O',
    'P','Q','R','S','T','V','W','X','Y','Z','1','2',
    '3','4','5','6','7','8','9','0'
);

function key_increment (&$symbols, $position = null) 
{
    global $a;
    if ($position === null) $position = count($symbols) - 1;
    if ($position == -1) return;

    $index = $symbols[$position];
    $index ++;
    if (!isset($a[$index])) {
        $v = 0;
        key_increment ($symbols, $position-1);
    }
    $symbols[$position] = $value;
}

function generate($length, $total) 
{
    global $a;

    $symbols = array_fill(0, $length, 0);


        for ($i = 0; $i < $total; $i ++) {
            $code = '';
        foreach ($symbols as $index) {
            $code .= $a[$index];
        }
        echo $code;
        echo '<br />';

        key_increment($symbols);
    }
}

generate(3, 100);
于 2012-08-24T08:47:36.463 回答
0

最好只使用 uniqid,尤其是看到您说您将生成 160 万个代码。如果您担心这种情况,只需使用 strtoupper()

echo strtoupper(uniqid());

生成所有这些并插入它们将需要相当长的时间。

于 2012-08-24T08:37:16.717 回答