PHP组合二乘二

时间:2017-11-23 10:29:27

标签: php arrays combinations

我搜索了网站,但找不到我需要的内容,我不知道该怎么做这个代码。 我需要一个脚本来制作数组中的所有组合

例如我有这个数组:

$players = ('1', '2', '3', '4', '5');

我需要这个输出

1 - 2
1 - 3
1 - 4
1 - 5
2 - 3
2 - 4
2 - 5
3 - 4
3 - 5
4 - 5

提前致谢

6 个答案:

答案 0 :(得分:7)

  $players = array('1', '2', '3', '4', '5');

          for($i=0;$i<sizeof($players)-1;$i++){
               for($j=$i;$j<sizeof($players);$j++){
                   if( $players[$i]!= $players[$j]){
                          echo  '<br/>';
                       echo $players[$i].' - '.$players[$j];
                   }
              }
          }

输出 -

1 - 2
1 - 3
1 - 4
1 - 5
2 - 3
2 - 4
2 - 5
3 - 4
3 - 5
4 - 5

答案 1 :(得分:2)

$players = array('1','2','3','4','5');

while(count($players) != 0){
    $currentPlayer = array_shift($players);
    foreach($players as $player){
        echo $currentPlayer.' - '.$player.'<br/>';
    }
}

编辑:即使播放器数量不连续,我的代码也能正常运行。 $ players数组看起来像$players = ('1','5','209','42');,仍然打印出所需的输出。

答案 2 :(得分:0)

简单方法: -
 

function combinations($arr, $n)
{
    $res = array();

    foreach ($arr[$n] as $item)
    {
        if ($n==count($arr)-1)
            $res[]=$item;
        else
        {
            $combs = combinations($arr,$n+1);

            foreach ($combs as $comb)
            {
                $res[] = "$item $comb";
            }
        }
    }
    return $res;
}

$words = array(array('A','B'),array('C','D'), array('E','F'));

$combos = combinations($words,1);  
echo '<pre>';
print_r($combos);
echo '</pre>';
?>
  

输出: -

Array
(
    [0] => C E
    [1] => C F
    [2] => D E
    [3] => D F
)

答案 3 :(得分:-1)

试试这个:

<?php
  $arr = array('1','2', '3', '4', '5');

  for($i;$i<=count($arr);$i++){
    for($y=$i+1;$y<count($arr); $y++){
       echo ($i+1).'-'.$arr[$y].PHP_EOL;
    }
  }
?>

答案 4 :(得分:-1)

    $players = array('1', '3', '5', '7', '9');

    for($i=0; $i<count($players); $i++) {
        for($j=$i+1; $j<count($players); $j++){
            echo ($players[$i]).' - '.$players[$j].PHP_EOL;
        }
    }

这适用于数组中的任何值

答案 5 :(得分:-3)

一个foreach循环和一个以foreach值+1开始的for循环。

$players =array ('1', '2', '3', '4', '5');

Foreach($players as $player){

    For($i=$player+1; $i<=count($players); $i++){
        Echo $player ."-" .$i."\n";
    }
}

https://3v4l.org/Bunia