好的,这是您的代码(顺便说一句,感谢您发布了这样一个有趣且具有挑战性的问题-至少对我来说… :-))- 在给定元素数组的情况下,对所有可能的排列
使用递归 (按N))
代码:
<?phpfunction 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;}// Your array$words = array('cat','dog','fish');// Get permutation by groups of 3 elements$pe = permutations($words,3);// Print it outprint_r($pe);?>输出:
Array( [0] => cat cat cat [1] => cat cat dog [2] => cat cat fish [3] => cat dog cat [4] => cat dog dog [5] => cat dog fish [6] => cat fish cat [7] => cat fish dog [8] => cat fish fish [9] => dog cat cat [10] => dog cat dog [11] => dog cat fish [12] => dog dog cat [13] => dog dog dog [14] => dog dog fish [15] => dog fish cat [16] => dog fish dog [17] => dog fish fish [18] => fish cat cat [19] => fish cat dog [20] => fish cat fish [21] => fish dog cat [22] => fish dog dog [23] => fish dog fish [24] => fish fish cat [25] => fish fish dog [26] => fish fish fish)
提示: 通过
permutations($words,2),您将完全可以得到想要的…



