PHP生成字符组合方法
本示例展示了如何使用PHP生成给定字符集合中指定长度的所有组合情况,供开发者参考学习。
假设输入一组字符,目标是生成这些字符在特定长度下的所有排列组合:
例如输入字符包括 a,b,c,d,e 或者数字序列 0-9。
当设定长度为1时,结果为单个字符如 a, b, c, d, e;若长度为2,则包含 aa, ab, ac, ad, ae, ba, bb, bc, bd, be 直至 ee 的所有两两组合。
<?php
function de($len, $pos = 0) {
static $bit = [];
static $source = ['a', 'b', 'c', 'd', 'e'];/*[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];*/
$pos++;
for($i = 0; $i < count($source); $i++) {
$bit[$pos] = $source[$i];
if ($pos < $len) {
de($len, $pos);
} else {
echo implode('', $bit)."\n";
}
}
}
可使用 phpcmd 工具(访问 https://github.com/dclnet/phpcmd)执行以下代码。

上述输出对应长度为1的情况。

接下来展示长度为2时的结果。
希望该示例对掌握PHP程序设计有所帮助。