代码之家  ›  专栏  ›  技术社区  ›  Cristian Longo

PHP组合二乘二

  •  -2
  • Cristian Longo  · 技术社区  · 7 年前

    我搜索了这个网站,但我找不到我需要的,我不知道如何做这个代码。 我需要一个脚本来生成数组中的所有组合

    例如,我有一个数组:

    $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 回复  |  直到 7 年前
        1
  •  2
  •   kscherrer    7 年前
    $players = array('1','2','3','4','5');
    
    while(count($players) != 0){
        $currentPlayer = array_shift($players);
        foreach($players as $player){
            echo $currentPlayer.' - '.$player.'<br/>';
        }
    }
    

    编辑: 我的代码可以工作,即使playerNumber是非连续的。$players数组可以如下所示 $players = ('1','5','209','42'); 并且仍然打印出所需的输出。

        2
  •  0
  •   Harveer Singh Aulakh    7 年前

    简单方式:--

    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
  •  0
  •   Krishan Kumar    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
    
        4
  •  -1
  •   Fky    7 年前

    试试这个:

    <?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;
        }
      }
    ?>
    
        5
  •  -1
  •   MaK    7 年前
        $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;
            }
        }
    

    这适用于数组中的任何值

        6
  •  -3
  •   Andreas    7 年前

    一个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