在PHP中没有重复的有序组合?

时间:2013-09-25 09:16:57

标签: php combinations

我有以下数组:

数组(“一个”,“两个”,“三个”,“四个”);

我需要一个函数来输出数组元素的所有有序组合而不重复。输出应为

one
one two
one two three
one two three four
two
two three
two three four
three
three four
four

输出不应包括:

one one
one two four
two one three
four two three

等等......

你们有没有人已经实施过这种alghoritm?

1 个答案:

答案 0 :(得分:1)

这只是两个嵌套循环:

Online demo

function permutation(array $arr)
{
    while($ele=array_shift($arr))
    {
        $x=$ele;
        echo $x."\n";
        foreach($arr as $rest)
        {
            $x.=" $rest";
            echo $x."\n";
        }
    }
}
permutation(array("one","two","three","four"));