数组耗尽的允许内存大小为268435456个字节

时间:2014-06-22 15:11:24

标签: php arrays combinations memory-limit

我正在尝试创建一个函数来生成所有可能的组合。这部分效果很好,输出就是

AAA AAB AAC AAD ...

但是现在我想为每个组合添加一个扩展名,所以我想添加" HI"最后像

aaaHI aabHI aacHI 阿地

我试过以下但是我得到了这个错误。有没有更好的方法来做我正在做的事情?

致命错误:允许的内存大小为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>";
} 

1 个答案:

答案 0 :(得分:1)

这不是很清楚你要做什么,但首先,你错误地使用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;
}