我知道这是一个很老的帖子,但另一个答案不是很灵活,所以我想我会带来一个新的答案。
说明
所以你正在寻找所有的组合:
(2n) - 1
在您的具体示例中是:
(23) - 1 = (8) - 1 = 7
那么我现在如何获得所有组合?我们循环遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”($results = [[]];)),对于每个组合,我们遍历数组中的下一个单词并将每个组合与每个新组合词到一个新的组合。
示例
Array with the words/numbers (Empty array is '[]'):
[1, 2, 3]
//↓new combinations for the next iteration
│
iteration 0:
Combinations:
- [] │ -> []
│
iteration 1: ┌─────────────┤
│ │
Combinations: v v
- [] + 1 │ -> [1]
│
iteration 2: ┌─────────────┤
│ │
Combinations: v v
- [] + 2 │ -> [2]
- [1] + 2 │ -> [1,2]
│
iteration 3: ┌─────────────┤
│ │
Combinations: v v
- [] + 3 │ -> [3]
- [1] + 3 │ -> [1,3]
- [2] + 3 │ -> [2,3]
- [1,2] + 3 │ -> [1,2,3]
//^ All combinations here
所以你可以看到总有:(2^n)-1 组合。同样通过这种方法,组合数组中还剩下一个空数组,因此在返回数组之前,我只需使用array_filter() 删除所有空数组并使用array_values() 重新索引整个数组。
代码
<?php
$str = "how are you";
function getCombinations($array) {
//initalize array
$results = [[]];
//get all combinations
foreach ($array as $k => $element) {
foreach ($results as $combination)
$results[] = $combination + [$k => $element];
}
//return filtered array
return array_values(array_filter($results));
}
$arr = getCombinations(explode(" ", $str));
foreach($arr as $v)
echo implode(" ", $v) . "<br />";
?>
输出:
how
are
how are
you
how you
are you
how are you