有没有办法对数组块进行排序,以便某些值不在同一块中?

问题描述 投票:0回答:1

我正在从事一个九人三队的选秀项目。我正在尝试理清逻辑。但是,我遇到了两个问题,希望得到一些帮助。

我有很多球员。玩家名称设置为键,玩家类型设置为值。它看起来像这样:

$players = array("Player 1" => "Mentor",
                 "Player 2" => "Mentor",
                 "Player 3" => "Mentor",
                 "Player 4" => "Player",
                 "Player 5" => "Player",
                 "Player 6" => "Player",
                 "Player 7" => "Player",
                 "Player 8" => "Player");

一共有3个队伍,每个队伍只能有1名“导师”。

我首先担心的是我的数组输出没有正确获取玩家名称。

我的第二个问题是我不确定如何合理地为每个团队设置 1 位导师。

看了几篇文章后,我知道 array_chunk 可以使用第三个设置的 true 选项来存储以前的键,但它似乎仍然不起作用。这是到目前为止的整个脚本:

$players = array("Player 1" => "Mentor",
                 "Player 2" => "Mentor",
                 "Player 3" => "Mentor",
                 "Player 4" => "Player",
                 "Player 5" => "Player",
                 "Player 6" => "Player",
                 "Player 7" => "Player",
                 "Player 8" => "Player");
shuffle($players);
$max_players = 3;
$teams = array_chunk($players,$max_players,true);
$teamno = 1;
for ($i = 0; $i < $max_players; $i++) {
    $teamcheck = $teams[$i];
    echo 'Team '.$teamno.'<br>';
    foreach ($teamcheck as $name => $type) {
        echo $name;
    }
    echo "<br><br>";
    $teamno++;
}

对于我的第一个担心,输出没有正确抓取玩家名称,它似乎抓取了 0-7 的关键值,而没有随机播放。它输出以下内容:

Team 1
012

Team 2
345

Team 3
67

但是,如果我在 echo 中将 $name 更改为 $type,它会正确地洗牌,但只显示玩家类型,而不显示名称。它输出以下内容:

Team 1
PlayerMentorPlayer

Team 2
MentorPlayerMentor

Team 3
PlayerPlayer

如何让它正确显示玩家姓名,并且正确洗牌?

我如何实现逻辑,以便如果该块部分中已存在 Mentor 类型,则仅引入其他两个 Player 类型,然后继续?

php
1个回答
0
投票

array_chunk()
不是一个好的选择,因为它不会均匀分配玩家。例如,如果您有七名玩家,那么您最终会得到两支三人队和一支一队,而您可能会想要一支三人队和两支两人队。

我首先将导师和玩家分成单独的数组,然后对它们进行洗牌:

<?php

$all = array('Player 1' => 'Mentor',
             'Player 2' => 'Mentor',
             'Player 3' => 'Mentor',
             'Player 4' => 'Player',
             'Player 5' => 'Player',
             'Player 6' => 'Player',
             'Player 7' => 'Player',
             'Player 8' => 'Player');

// separate the Players and Mentors into their own arrays
foreach ($all as $name => $type) {
    if ($type == 'Mentor') {
        $mentors[] = ['name' => $name, 'type' => $type];
    } else {
        $players[] = ['name' => $name, 'type' => $type];
    }
}

shuffle($mentors);
shuffle($players);

然后计算队伍数量:

$max_players = 3;
$total_players = count($all);
$num_teams = ceil($total_players / $max_players);

最后,在团队之间分配导师和选手:

for ($i = 0; $i < $total_players; $i++) {
    $team = $i % $num_teams;
    $teams[$team][] = array_pop($mentors) ?? array_pop($players);
}

这是一个演示 3v4l.org.

© www.soinside.com 2019 - 2024. All rights reserved.