代码之家  ›  专栏  ›  技术社区  ›  Paul

如何在php shuffle中组合两个数组

  •  0
  • Paul  · 技术社区  · 7 年前

    我正在尝试创建一个洗牌功能,让人们配对交换礼物。我创建了它的基本外壳,但我真的不知道该从这里走到哪里。我正在获取输出以洗牌数据,但是我希望将两者结合起来 array_give array_receive 变量,这样它将沿着以下线路输出:

    Paul&贝基正在给基思&杰基。

    不过,我不确定如何将这两者结合起来。这个 array\u give数组 变量不需要洗牌,只需要 array\u接收 变量执行。

    Paul&贝基正在给保罗&贝基

    HTML

    <button type="button" id="shuffle">Create Exchange</button>
    <div id="name-output"></div>
    

    JS公司

    $('#shuffle').on('click', function() {
            $.ajax({
                url: 'php/name-selection.php',
                type: 'POST',
                success: function(data) {
                    $('#name-output').html(data);
                },
                complete:function(){
    
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert(textStatus + '|' + errorThrown);
                }
            });
        })
    

    PHP

    $array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
    $array_receive = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
    
    shuffle($array_receive);
    
    foreach( $array_receive as $receiving) {
        echo $receiving . "<br>";
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Lawrence Cherone    7 年前

    由于数组本质上是相同的,因此只需要一个数组。

    然后,你可以在每次迭代中弹出/挑选每个元素,这将停止自我馈赠,并允许检查是否有人不会收到礼物,呸,骗子!

    <?php
    $array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
    
    shuffle($array_give);
    
    $i = 0;
    while ($give = array_pop($array_give)) {
        echo $give;
        if ($i % 2 != 0) {
            echo "<br>".PHP_EOL;
        } elseif (count($array_give) == 0) {
            echo ' is getting zilch! ';
            break;
        } else {
            echo ' are giving to ';
        }
        $i++;
    }
    

    .

    Rob & Savannah are giving to Ashley & Jeric<br>
    Dave & Lauren are giving to Keith & Jackie<br>
    Paul & Becky is getting zilch! 
    

    https://3v4l.org/KtJ47

        2
  •  1
  •   jh1711    7 年前

    组合到数组的函数被调用 array_combine . 你可以看看 here ,并这样使用:

    <?php
    function checkSame ($a, $b) {
      foreach (array_combine($a,$b) as $key => $value)
        if ($key===$value) return true;
      return false;
    }
    
    $array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
    $array_receive = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
    
    while (checkSame($array_give, $array_receive)) shuffle($array_receive);
    
    foreach( array_combine($array_give, $array_receive) as $give => $receiving) 
    {
      echo $give. " give to ".$receiving . "<br>";
    }
    

    我的想法是防止自我馈赠,只需继续洗牌数组,直到没有人分配给自己。从理论上讲,这可能会永远持续下去,但我认为在大多数实际应用中,它会很快停止。