【问题标题】:Getting all possible combination of an array获取数组的所有可能组合
【发布时间】:2016-01-18 13:29:49
【问题描述】:

我有一个包含以下值的数组

$in = array("A","B","C","D","E");

我想通过指定的 (n) 编号获得所有可能的组合。

例如,如果 n = 2,则返回 AB、AC、AD、AE、BC、BD、BE、CD、CE、DE

如果 n = 3,则返回 ABC、ABD、ABE、BCD、BCE、CDE

请问,我如何在 PHP 中实现这一点?

【问题讨论】:

  • 你能展示一下你已经尝试和取得的成就吗?还有为什么要标记 Javascript 和 jQuery?
  • 如果您使用 Google 进行研究,这个特定的家庭作业有很多解决方案。

标签: php arrays


【解决方案1】:
function sampling($chars, $size, $combinations = array()) {

  # if it's the first iteration, the first set 
  # of combinations is the same as the set of characters
  if (empty($combinations)) {
    $combinations = $chars;
  }

  # we're done if we're at size 1
  if ($size == 1) {
    return $combinations;
  }

  # initialise array to put new values in
  $new_combinations = array();

  # loop through existing combinations and character set to create strings
  foreach ($combinations as $combination) {
    foreach ($chars as $char) {
      $new_combinations[] = $combination . $char;
    }
  }

  # call same function again for the next iteration
  return sampling($chars, $size - 1, $new_combinations);

}

// example
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);

更多信息here

【讨论】:

    猜你喜欢
    • 2013-10-06
    • 1970-01-01
    • 2012-03-20
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多