这个问题已经以多种形式提出。我想在PHP中使用数组并获得所有可能的组合/排列。我想要整个集合的排列以及部分集合。
我对此问题的看法是询问如何从结果项中删除连续重复项。通过使用“PHP take all combinations”并添加一个函数,我接近了我想要的东西:
$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
相同(如果设置较大)注意:
答案 0 :(得分:0)
您可以将permutations数组作为reference(带有正在进行的&符号)作为permutations()的第三个参数传递,并在添加值之前运行in_array()检查。然而,这比在get_all_permutation()
结束时删除重复项要差得多。