获得数组

时间:2016-01-18 13:29:49

标签: php arrays

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

$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中实现这一目标?

1 个答案:

答案 0 :(得分:0)

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