如何在 PHP 中获取和生成重复数字(子集)数组

我检查了代码并意识到它不能显示重复的数字


我的代码


      <?php


      /* Designated level for each exp

      Level 2 - 23 exp

      Level 3 - 34 exp

      Level 4 - 45 exp

      Level 5 - 56 exp

      Level 6 - 68 exp

      Level 7 - 79 exp

      Level 8 - 90 exp

      Level 9 - 101 exp

      Level 10 - 112 exp

      Level 11 - 123 exp

      Level 12 - 134 exp

      Level 13 - 145 exp

      Level 14 - 156 exp

      Level 15 - 168 exp

      Level 16 - 179 exp

      */


      $limit =  100000-99370;


      // Level

      $arrlevel = array ('Level 2','Level 3','Level 4','Level 5','Level 6','Level 7','Level 8','Level 9','Level 10','Level 11','Level 12','Level 13','Level 14','Level 15','Level 16');


      // Exp

      $array = array (23,34,45,56,68,79,90,101,112,123,134,145,156,168,179);


      $array = array_filter($array, function($var) use ($limit) {

      return ($var <= $limit);

      });


      $num = count($array);

      $total = pow(2, $num);

      $out = array();


      for ($i = 0; $i < $total; $i++) {


      $comb = array();

      for ($j = 0; $j < $num; $j++) {

      // is bit $j set in $i?

      if (pow(2, $j) & $i){

      $comb[] = $array[$j];

      }

      }


      if (array_sum($comb) == $limit)

      {

      $out[] = $comb;

      }

      }


      array_multisort(array_map('count', $out), SORT_ASC, $out);


      $out = array_unique($out, SORT_REGULAR);

      ];



我的输入和输出


如果我输入 99318

输出是这样的

可能的答案 1:

级别 10 - 112 ,级别 11 - 123 ,级别 12 - 134 ,级别 13 - 145 ,级别 15 - 168

我也想生成重复的数字


但它不能显示像这样的重复数字答案

可能的答案:

级别 4 - 45 ,级别 10 - 112 ,级别 11 - 123 ,级别 11 - 123 ,级别 12 - 134 ,级别 13 - 145


您可以看到有两个级别 11 - 123




我想要这样的输出


可能的答案:

级别 4 - 45 ,级别 10 - 112 ,级别 11 (x2) - 246 ,级别 12 - 134 ,级别 13 - 145

我想对所有重复数字进行分组并汇总它们


Smart猫小萌
浏览 244回答 1
1回答

繁星点点滴滴

获得结果的一种选择是将另一个值与 array_count_values 的结果一起传递给array_map。然后在映射中,您可以确定显示基于索引的数字计数,就像$countValues[$x]映射器一样。例如foreach($out as $result) {&nbsp; &nbsp; $countValues = array_count_values($result);&nbsp; &nbsp; echo "<b>Possible Answer " . $m++ . " : </b><br> " . implode(' , ',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array_map(function ($x) use ($mapper, $countValues) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $strCount = $countValues[$x] > 1 ? " (" . $countValues[$x] . ")" : "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $mapper[$x] . $strCount . " - " . $x;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, array_unique($result))) . "&nbsp; &nbsp; &nbsp; <br><br>";}这会给你一个结果Possible Answer 1 :Level 2 - 23 , Level 6 - 68 , Level 7 (x2) - 79 , Level 9 - 101 , Level 10 - 112 , Level 15 - 168&nbsp;Php 演示,作为测试重复值 79$array
打开App,查看更多内容
随时随地看视频慕课网APP