-1
$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.

我做错什么了吗?

4

2 回答 2

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/>";
    }
  }
}
于 2013-11-10T16:58:05.867 回答
0

有点...

foreach($num AS $value1)
{
  foreach($num AS $value2)
  {
    foreach($num AS $value3)
    {
      echo $value1 . ',' . $value2 . ',' . $value3 . '<br>';
    }
  }
}
于 2013-11-10T16:54:21.400 回答