如何列出所有可能的组合?

时间:2013-11-10 16:51:14

标签: php arrays

$num = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

在数组$ num中有10个数字。我想用PHP列出所有可能的3号组合。 就像:

1, 2, 3
1, 2, 4
1, 2, 5
etc

修改
感谢所有答案,但如果我想创建6个数字组合,则会出现问题。

$num_array2 = array(1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 15, 16, 18, 19, 20);

foreach($num_array2 AS $value1) {
    foreach($num_array2 AS $value2) {
        if($value2 == $value1) {
            continue;
        }
        foreach($num_array2 AS $value3) {
            if($value3 == $value1 || $value3 == $value2) {
                continue;
            }
            foreach($num_array2 AS $value4) {
                if($value4 == $value1 || $value4 == $value2 || $value4 == $value3) {
                    continue;
                }
                foreach($num_array2 AS $value5) {
                    if($value5 == $value1 || $value5 == $value2 || $value5 == $value3 || $value5 == $value4) {
                        continue;
                    }
                    foreach($num_array2 AS $value6) {
                        if($value6 == $value1 || $value6 == $value2 || $value6 == $value3 || $value6 == $value4 || $value6 == $value5) {
                            continue;
                        }
                        echo "$value1, $value2, $value3, $value4, $value5, $value6 \n<br />";
                    }
                }
            }
        }
    }
}

我无法列出

1, 2, 3, 4, 5, 6
1, 2, 3, 4, 5, 7
etc.

我做错了吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

foreach($num AS $value1)
{
  foreach($num AS $value2)
  {
    if($value2 == $value1){
      continue;
    }
    foreach($num AS $value3)
    {
      if($value3 == $value1 || $value3 == $value2){
        continue;
      }
      echo "$value1, $value2, $value3<br/>";
    }
  }
}

修改

实际上,前面的代码列出了所有排列而不是组合。如果您想要所有组合,请尝试以下方法:

for($value1 = 1; $value1 <= 10; $value1++){
  for($value2 = $value1 + 1; $value2 <= 10; $value2++){
    for($value3 = $value2 + 1; $value3 <= 10; $value3++){
      echo "$value1, $value2, $value3<br/>";
    }
  }
}

答案 1 :(得分:0)

有些事情......

foreach($num AS $value1)
{
  foreach($num AS $value2)
  {
    foreach($num AS $value3)
    {
      echo $value1 . ',' . $value2 . ',' . $value3 . '<br>';
    }
  }
}