CombinationService.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Services;
  11. class CombinationService
  12. {
  13. public static function combination($arr, $num)
  14. {
  15. $r = array();
  16. $n = count($arr);
  17. if ($num <= 0 || $num > $n) {
  18. return $r;
  19. }
  20. for ($i = 0; $i < $n; $i++) {
  21. $t = array($arr[$i]);
  22. if ($num == 1) {
  23. $r[] = $t;
  24. } else {
  25. $b = array_slice($arr, $i + 1);
  26. $c = self::combination($b, $num - 1);
  27. foreach ($c as $v) {
  28. $r[] = array_merge($t, $v);
  29. }
  30. }
  31. }
  32. return $r;
  33. }
  34. public static function combinationALL($array, $level = -1, &$list = [])
  35. {
  36. for ($i = 0; $i < count($array); $i++) {
  37. if ($level < 0) {
  38. //第一级直接输出对应数字
  39. $list[][] = $array[$i];
  40. } else {
  41. $values = $array[$i];
  42. //根据等级组装前几位
  43. for ($k = 0; $k < $level; $k++) {
  44. $values .= '+' . $array[$i + $k + 1];
  45. }
  46. $j = 0;
  47. //循环拼合最后一位
  48. for ($n = ($i + $level + 1); $n < count($array); $n++) {
  49. $j++;
  50. $first = $values; // 组合上几位
  51. $first .= '+' . $array[$n];
  52. $list[] = str2arr($first, '+');
  53. }
  54. //到最后一位结束递归
  55. if ($j == 1) {
  56. break;
  57. }
  58. }
  59. }
  60. //长度大于等级+2停止递归
  61. if (($level + 2) < count($array)) {
  62. self::combinationALL($array, $level + 1, $list);
  63. }
  64. return $list;
  65. }
  66. }