PHP:如何获得一维数组元素取1-N个元素的所有可能排列

  • A+
所属分类:PHP日常 数组
  1. <?php
  2.  
  3. $array = array('Alpha', 'Beta', 'Gamma', 'Sigma');
  4.  
  5. function depth_picker($arr, $temp_string, &$collect) {
  6. if ($temp_string != "")
  7. $collect []= $temp_string;
  8.  
  9. for ($i=0, $iMax = sizeof($arr); $i < $iMax; $i++) {
  10. $arrcopy = $arr;
  11. $elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
  12. if (sizeof($arrcopy) > 0) {
  13. depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
  14. } else {
  15. $collect []= $temp_string. " " . $elem[0];
  16. }
  17. }
  18. }
  19.  
  20. $collect = array();
  21. depth_picker($array, "", $collect);
  22. print_r($collect);
  23.  
  24. ?>
  25.  
  1. 结果
  2.  
  3.  
  4. Array
  5. (
  6. [0] => Alpha
  7. [1] => Alpha Beta
  8. [2] => Alpha Beta Gamma
  9. [3] => Alpha Beta Gamma Sigma
  10. [4] => Alpha Beta Sigma
  11. [5] => Alpha Beta Sigma Gamma
  12. [6] => Alpha Gamma
  13. [7] => Alpha Gamma Beta
  14. [8] => Alpha Gamma Beta Sigma
  15. [9] => Alpha Gamma Sigma
  16. [10] => Alpha Gamma Sigma Beta
  17. [11] => Alpha Sigma
  18. [12] => Alpha Sigma Beta
  19. [13] => Alpha Sigma Beta Gamma
  20. [14] => Alpha Sigma Gamma
  21. [15] => Alpha Sigma Gamma Beta
  22. [16] => Beta
  23. [17] => Beta Alpha
  24. [18] => Beta Alpha Gamma
  25. [19] => Beta Alpha Gamma Sigma
  26. [20] => Beta Alpha Sigma
  27. [21] => Beta Alpha Sigma Gamma
  28. [22] => Beta Gamma
  29. [23] => Beta Gamma Alpha
  30. [24] => Beta Gamma Alpha Sigma
  31. [25] => Beta Gamma Sigma
  32. [26] => Beta Gamma Sigma Alpha
  33. [27] => Beta Sigma
  34. [28] => Beta Sigma Alpha
  35. [29] => Beta Sigma Alpha Gamma
  36. [30] => Beta Sigma Gamma
  37. [31] => Beta Sigma Gamma Alpha
  38. [32] => Gamma
  39. [33] => Gamma Alpha
  40. [34] => Gamma Alpha Beta
  41. [35] => Gamma Alpha Beta Sigma
  42. [36] => Gamma Alpha Sigma
  43. [37] => Gamma Alpha Sigma Beta
  44. [38] => Gamma Beta
  45. [39] => Gamma Beta Alpha
  46. [40] => Gamma Beta Alpha Sigma
  47. [41] => Gamma Beta Sigma
  48. [42] => Gamma Beta Sigma Alpha
  49. [43] => Gamma Sigma
  50. [44] => Gamma Sigma Alpha
  51. [45] => Gamma Sigma Alpha Beta
  52. [46] => Gamma Sigma Beta
  53. [47] => Gamma Sigma Beta Alpha
  54. [48] => Sigma
  55. [49] => Sigma Alpha
  56. [50] => Sigma Alpha Beta
  57. [51] => Sigma Alpha Beta Gamma
  58. [52] => Sigma Alpha Gamma
  59. [53] => Sigma Alpha Gamma Beta
  60. [54] => Sigma Beta
  61. [55] => Sigma Beta Alpha
  62. [56] => Sigma Beta Alpha Gamma
  63. [57] => Sigma Beta Gamma
  64. [58] => Sigma Beta Gamma Alpha
  65. [59] => Sigma Gamma
  66. [60] => Sigma Gamma Alpha
  67. [61] => Sigma Gamma Alpha Beta
  68. [62] => Sigma Gamma Beta
  69. [63] => Sigma Gamma Beta Alpha
  70. )