我有一个包含三个元素的数组 $base =
(#m, #f,#p)
我有第二个数组,其中包含任意数量的元素,例如 $var = (s1, s2)
现在我需要仅根据基本数组创建所有可能的组合。我找到的公式是 x pow y
。
在这个例子中,我的基本数组有三个元素,$var
有 2,所以 pow(3, 2)
是 9。我需要这九种组合。即
#m#m #m#f #m#p
#f#m #f#f #f#p
#p#m #p#f #p#p
第二个数组中的元素数量实际上是生成的组合的长度。在此示例中,第二个数组的长度为 2,因此所有生成的字符串的长度均为 2。
最佳答案
你可以像这样使用递归函数:
// 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;
}
关于php - php中x pow y的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12369443/