本文介绍了有条件的随机但唯一的配对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设置PHP脚本以随机配对数组中的项目时,我需要一些帮助/指导.

I need some help/direction in setting up a PHP script to randomly pair up items in an array.

  • 每次都应将物品随机配对.

  • The items should be randomly paired up each time.

项目不应该匹配(项目1-1不应与项目1-1配对)

The items should not match themselves ( item1-1 should not pair up with item1-1 )

大多数具有配对对象( item1-1和item1-2).这些物品不应与其伴侣配对.

Most of the items have a mate (ie. item1-1 and item1-2). The items should not be paired with their mate.

我一直在玩,但是我没有任何进展.感谢您的帮助.

I've been playing around with the second script in this post but, I haven't been able to make any progress. Any help is appreciated.

推荐答案

非常简单的方法,但希望对您有所帮助:

Very simple approach, but hopefully helpful to you:

( mates ,如果分组在一个数组中(例如 array('a1','a2')),则不会配对.)

(mates, if grouped in an array (e.g. array('a1', 'a2')), will not be paired.)

function matchUp($array) {
  $result = array();

  while($el = array_pop($array)) {
    shuffle($array);

    if (sizeof($array) > 0) {
      $candidate = array_pop($array);

      $result[] = array(
        array_pop($el),
        array_pop($candidate)
      );

      if (sizeof($el) > 0) {
        $array[] = $el;
      }

      if (sizeof($candidate) > 0) {
        $array[] = $candidate;
      }
    }
    else {
      $result[] = array(array_pop($el));
    }
  }

  return $result;
}

$array = array(
  array('a1', 'a2'),
  array('b1', 'b2'),
  array('c1'),
  array('d1'),
  array('e1', 'e2'),
  array('f1'),
  array('g1', 'g2'),
);

更新:

foreach(matchUp($array) as $pair) {
  list($a, $b) = $pair + array(null, null);
  echo '<div style="border: solid 1px #000000;">' . $a . ' + ' . $b . '</div>';
}

这篇关于有条件的随机但唯一的配对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 07:20