在php中所有x pow y的组合

use*_*914 6 php math combinations

我有一个有三个元素的数组 $base =(#m, #f,#p)

我有第二个数组有任意数量的元素 $var = (s1, s2)

现在我需要根据基本数组创建所有可能的组合.我发现的公式是x pow y.

在这个例子中,我的基本数组有三个元素,$var2个,所以 pow(3, 2)9.我需要这九种组合.即

#m#m #m#f #m#p
#f#m #f#f #f#p
#p#m #p#f #p#p
Run Code Online (Sandbox Code Playgroud)

第二个数组中的元素数量实际上是生成的组合的长度.在此示例中,第二个数组的长度为2,因此所有生成的字符串都具有长度2.

Asc*_*iom 4

您可以使用这样的递归函数:

// input definition
$baseArray = array("#m", "#f", "#p");
$varArray = array("s1", "s2", "s3");

// call the recursive function using input
$result = recursiveCombinations($baseArray, sizeof($varArray));

// loop over the resulting combinations
foreach($result as $r){
    echo "<br />combination " . implode(",", $r);
}

// this function recursively generates combinations of #$level elements
// using the elements of the $base array
function recursiveCombinations($base, $level){
    $combinations = array();
    $recursiveResults = array();

    // if level is > 1, get the combinations of a level less recursively
    // for level 1 the combinations are just the values of the $base array
    if($level > 1){
        $recursiveResults = recursiveCombinations($base, --$level);
    }else{
        return $base;   
    }
    // generate the combinations
    foreach($base as $baseValue){
        foreach($recursiveResults as $recursiveResult){
            $combination = array($baseValue);
            $combination = array_merge($combination, (array)$recursiveResult);  
            array_push($combinations, $combination);
        }
    }
    return $combinations;
}
Run Code Online (Sandbox Code Playgroud)

工作键盘演示