我有一个数组,它有三个元素$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
$strs = Array("some", "thing", "here");
$poss = Array(1, 2);
$new = Array();
for($i = 0; $i < pow(count($strs), count($poss)); $i++) {
for($j = 0; $j < count($strs); $j++) {
$new[$i] = $strs[($i%count($strs))] . " " . $strs[$j];
}
}
print_r($new);
?>
正在工作的代码板链接(对于给定的示例)。
链接
- pow(4,3)
- pow(4,2)
- pow(3,5)