PHP 将数组随机匹配到自身中


PHP match an array into itself randomatically

sample 数组:

$player = array("lawrence","joey","jason","joel","bianca","paulo","albert");

我想将数组与自身匹配,以便它从自身获取值而不会获得重复的值:

"lawrence" => "lawrence"; //must not contain itself
"joey" => "lawrence"; //must not assign value already assigned to that value

简而言之:它就像一个交换礼物算法

$player = array("lawrence","joey","jason","joel","bianca","paulo","albert");
shuffle($player);
$player2 = $player;
array_unshift($player2, array_pop($player2));
$combined = array_combine($player, $player2);

洗牌,将其转置 1 以创建有保证的唯一匹配,重新组合。

我找到了这篇文章:使用PHP,随机配对一组项目,不与自身配对,不直接配对

而最上面的答案看起来非常好:https://stackoverflow.com/a/3758775/623952

// result array
$res = array();
// get first element and save it
$first = $ele1 = array_shift($arr);
while(count($arr)) {
    // get random element
    $ele2 = array_rand($arr);
    // associate elements
    $res[$ele1] = $arr[$ele2];
    // random element becomes next element
    $ele1 = $arr[$ele2];
    // delete the random element
    array_splice($arr, $ele2, 1);
}
// associate last element woth the first one
$res[$ele1] = $first;

这给了我:

Array
(
    [lawrence] => joel
    [joel] => joey
    [joey] => jason
    [jason] => paulo
    [paulo] => albert
    [albert] => bianca
    [bianca] => lawrence
)

您可能需要在那里签到,看看您的礼物交换中"这个人是否选择了自己"。