如何生成4个数字和2个A-Z字符的图案的每种组合

时间:2019-05-30 18:57:42

标签: php loops combinations

我写了一个小脚本来与我从朋友那里得到的数据库进行对话,因此我可以将荷兰邮政编码与街道名称链接起来。但我想自己做

邮政编码的构建方式类似于NNNNCC,其中N是数字0-9(不能忽略前0个数字0000-0999),而C =字符AZ。

如何在PHP中生成所有可能的组合?

3 个答案:

答案 0 :(得分:3)

简单的foreach嵌套循环为:

foreach(range(1000,9999) as $num)
    foreach(range('A', 'Z') as $c1) 
        foreach(range('A', 'Z') as $c2)
            $res[] = $num . $c1 . $c2; 

我不在我的电脑上,因此对语法错误(如果有的话)感到抱歉(您可能需要将$num转换为字符串,但是我想PHP会处理它...

答案 1 :(得分:1)

以@dWinder答案为基础。您可以建立一个列表。

foreach(range(0,9999) as $num)
    foreach(range('A', 'Z') as $c1) 
        foreach(range('A', 'Z') as $c2)
//      This comes out to 6,760,000 items
//          $zips[] = sprintf("%04s%s%s<br>", $num, $c1, $c2); 

如果只想检查格式,则可以进行模式匹配。

echo testZipNl('1t00AA') .' 1t00AA<br>';

echo testZipNl('11000AA') .' 11000AA<br>';

echo testZipNl('1000AA') .' 1000AA<br>';


function testZipNl($input){
    $input = trim($input);
    $regex = "/^[0-9]{4}[A-Z]{2}$/";
    if (preg_match($regex, $input) AND strlen($input) == 6) {
     return 'True';
    }
 return 'False';
}

答案 2 :(得分:1)

您可以使用简单的类似寻呼机的功能来避免内存问题:

<?php

function codeRange(int $start, int $end) {
    $codes = [];
    $number = $start - 1;
    while ($number++ !== $end + 1) {
        $letter = 'AA';
        while ($letter !== 'AAA') {
            $codes[] = sprintf('%s%s', $number, $letter++);
        }
    }

    return $codes;
}

echo codeRange(1000, 1010)[0] . PHP_EOL;       // output: 1000AA
echo codeRange(1000, 1010)[1] . PHP_EOL;       // output: 1000AB
echo codeRange(1000, 1010)[2] . PHP_EOL;       // output: 1000AC
echo codeRange(1000, 1010)[7434] . PHP_EOL;    // output: 1010ZY
echo codeRange(1000, 1010)[7435] . PHP_EOL;    // output: 1010ZZ
echo codeRange(9979, 9998)[0] . PHP_EOL;       // output: 9979AA
echo codeRange(9979, 9998)[14195] . PHP_EOL;   // output: 9999ZZ