我试图做一个函数来生成所有可能的组合。这部分效果很好,所以输出将是
aaa aab aac aad ...
但是现在我正尝试为每个组合添加扩展名,因此我想在末尾添加“ HI”,例如
aaaHI aabHI aacHI aadHI
IV尝试以下内容,但即时通讯收到此错误。有什么更好的方法可以做到这一点吗?
致命错误:耗尽了268435456字节的允许的内存大小(尝试分配100663409字节)
这是我的剧本
function sampling($chars, $size, $combinations = array()) {
# if it's the first iteration, the first set
# of combinations is the same as the set of characters
if (empty($combinations)) {
$combinations = $chars;
}
# we're done if we're at size 1
if ($size == 1) {
return $combinations;
}
# initialise array to put new values in
$new_combinations = array();
# loop through existing combinations and character set to create strings
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination. $char;
$new_combinations[] = implode($new_combinations, "HI");
}
}
# call same function again for the next iteration
return sampling($chars, $size - 1, $new_combinations);
}
// example
$chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$output = sampling($chars, 3);
foreach($output as $do)
{
echo $do."<br>";
}
目前尚不清楚要做什么,但是首先,您使用implode()
不正确。第一个参数必须为$ glue,第二个参数为数组。
string implode ( string $glue , array $pieces )
其次,您的$ new_combinations数组在每个步骤中都在逐步增长。
但是,如果我了解您的打算,那么这段代码将为您工作:
<?php
function sampling($chars, $size, $combinations = array()) {
// if it's the first iteration, the first set
// of combinations is the same as the set of characters
if (empty($combinations)) {
$combinations = $chars;
}
// we're done if we're at size 1
if ($size == 1) {
return $combinations;
}
// initialise array to put new values in
$new_combinations = array();
// loop through existing combinations and character set to create strings
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$tmp = $combination. $char;
if ($size == 2) {
$tmp .= '.com';
}
$new_combinations[] = $tmp;
// I don't get what you were going to do with this line,
// but this looks like a logical bug in your code
//$new_combinations[] = implode(".com", $new_combinations);
}
}
// call same function again for the next iteration
return sampling($chars, $size - 1, $new_combinations);
}
// example
$chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$output = sampling($chars, 3);
foreach($output as $do)
{
echo $do."<br>".PHP_EOL;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句