这个问题已经以多种形式提出。我想在 PHP 中获取一个数组并获取所有可能的组合/排列。我想要整个集合和部分集合的排列。
我对这个问题的转折是询问如何从结果项中删除顺序重复项。通过使用“ PHP 采用所有组合”并添加一个函数,我接近了我想要的:
$words = array('a','b','c');
function permutations($arr,$n)
{
$res = array();
foreach ($arr as $w)
{
if ($n==1) $res[] = $w;
else
{
$perms = permutations($arr,$n-1);
foreach ($perms as $p)
{
$res[] = $w." ".$p;
}
}
}
return $res;
}
function get_all_permutations($words=array())
{
$r = array();
for($i=sizeof($words);$i>0;$i--)
{
$r = array_merge(permutations($words,$i),$r);
}
return $r;
}
$permutations = get_all_permutations($words);
print_r($permutations);
这将输出:
Array
(
[0] => a
[1] => b
[2] => c
[3] => a a
[4] => a b
[5] => a c
[6] => b a
[7] => b b
[8] => b c
[9] => c a
[10] => c b
[11] => c c
[12] => a a a
[13] => a a b
[14] => a a c
[15] => a b a
[16] => a b b
[17] => a b c
[18] => a c a
[19] => a c b
[20] => a c c
[21] => b a a
[22] => b a b
[23] => b a c
[24] => b b a
[25] => b b b
[26] => b b c
[27] => b c a
[28] => b c b
[29] => b c c
[30] => c a a
[31] => c a b
[32] => c a c
[33] => c b a
[34] => c b b
[35] => c b c
[36] => c c a
[37] => c c b
[38] => c c c
)
我知道一旦生成了集合,我就可以查看输出,但是是否可以在生成过程中删除顺序重复?
应该转换/删除的示例:
c c c
将与c
c c b
将与c b
c c c c c
也将与c
(如果集合更大)相同
笔记:
- 我不擅长递归,但可能有一种奇特的方法可以将我拥有的两个函数合二为一。
- 现在输出集是字符串,但我不介意它们是否是数组(如果这让事情变得更容易)