如何遍历数组,并删除具有最低值的键

How do I loop through an Array, and remove the key with lowest value

我正在尝试制作一个程序,该程序在分配了随机数的数组中具有不同的玩家。它是基于回合的,因此每一轮都会为玩家分配新的随机数,并且从数组中删除编号最小的玩家。

问题是在迭代时它不会从数组中删除编号最小的玩家。但是,它确实会打印出编号最低的玩家,但仅此而已...

我希望它移除一个或多个玩家并在每一轮显示他们的名字,直到剩下一个。

我是新手PHP,所以我的代码结构不是最好的xd

$players = array(
    
    "Peter" => "0",
    "John" => "0",
    "Harold" => "0",
    "Alexander" => "0",
    "Thor" => "0",
    "Paul" => "0",
    "Jimmy" => "0",
    "Erik" => "0",
    "Donald" => "0",
    "Matthew" => "0"
);

    for($i = 0; $i < count($players); $i++){
    
            echo "<br>" . "<b>Round ". (1 + $i) ."</b><br>";
    
            foreach($players as $key => $value){
               
                //generating random number to value 
                $value = rand(1,50);
               
                asort($players);  
    
                //Assigning each player a random number
                $players[$key]=$value; 
    
    
                $min = min($players);
                 
                array_splice($players,$min));    
                
            }
            
            echo "Player(s) with lowest number is: " .current(array_keys($players, min($players)));
            echo "<br>"
        }

我建议您使用 while 而不是 for-loop,例如:

$players = array(
    "Peter" => "0",
    "John" => "0",
    "Harold" => "0",
    "Alexander" => "0",
    "Thor" => "0",
    "Paul" => "0",
    "Jimmy" => "0",
    "Erik" => "0",
    "Donald" => "0",
    "Matthew" => "0"
);
$round = 1;
while (count($players) > 1) {
    echo "<br>" . "<b>Round " . $round . "</b><br>";

    foreach ($players as $key => $value) {    
        do {
            $value = rand(1, 50);
        } while(in_array($value, $players));
        $players[$key] = $value;
    }
    $key = array_keys($players, min($players))[0];
    echo "Player(s) with lowest number is: " . $key;
    echo "<br>";
    unset($players[$key]);
    $round++;
}
echo '<br>The winner is:'. key($players);

我改变了什么?

  • 使用 while 逻辑“继续直到数组计数为一”(所以只有赢家
  • 使用do-while为每个玩家生成不同的号码(唯一号码)
  • 找到数组的 min() 然后取消设置。

参考: