簡體   English   中英

PHP for 循環僅每第二行有效

[英]PHP for loop only works every second row

在我當前的項目中,我想將隊列中的 10 個用戶分成 2 個團隊,每個團隊 5 個用戶。

當隊列中有 10 個用戶時,執行 function create_new_lobby()。 在此 function 中,比賽已創建,所有用戶都應分配到中間表中的團隊。 使用 for 循環應將所有用戶分配給匹配項。 目前 for 循環只需要每隔一個用戶(0、2、4、6、8)。 for 循環顯然跳過了值 1、3、5、7 和 9。

這里的錯誤在哪里?

<?php 
function create_new_lobby() {

    global $connection;

    $timestamp = date("Y-m-d H:i:s", strtotime(date('h:i:sa')));

    $stmt = $connection->prepare("INSERT INTO competition_game (create_time) VALUES (?)");
    $stmt->bind_param("s", $timestamp);
    $stmt->execute();
    $stmt->close();

    $stmt = $connection->prepare("SELECT competition_match_id FROM competition_game ORDER BY competition_match_id DESC LIMIT 0, 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    $competition_match_id = $row['competition_match_id'];

    $stmt->close();

    for($player = 0; $player <= 9; $player++) {
        $status_queue = 1;
        $stmt = $connection->prepare("SELECT * FROM competition_queue WHERE competition_queue_status = ? AND DATE_ADD(competition_queue_activity ,INTERVAL 20 MINUTE) >= NOW() ORDER BY competition_queue_id ASC LIMIT ?, 1");
        $stmt->bind_param("ss", $status_queue, $player);
        $stmt->execute();
        $result = $stmt->get_result();

        while($row = $result->fetch_assoc()) {

            $user_id = $row['user_id'];

            $stmt1 = $connection->prepare("INSERT INTO competition_game_player (competition_match_id, user_id) VALUES (?, ?)");
            $stmt1->bind_param("ss", $competition_match_id, $user_id);
            $stmt1->execute();
            $stmt1->close();
        }

        $stmt->close();

        $status_leave = 2;
        $stmt = $connection->prepare("UPDATE competition_queue SET competition_queue_status = ? WHERE user_id = ? AND competition_queue_status = ?");
        $stmt->bind_param("sss", $status_leave, $user_id, $status_queue);
        $stmt->execute();
        $stmt->close();
    }
}
?>

當前結果: 當前數據庫輸出

預期結果: 預期結果

for 循環正常工作,您可以通過在 for 循環中放置一個var_dump($payer)來檢查它;

for 循環中的增量由第三個語句$player++給出,這意味着$player = $player + 1;

如果您想要不同的循環步驟,您可以為 for 循環中的第三條語句添加不同的表達式。

例如

for($player = 0; $player <= 9; $player++) {
    var_dump($player);
}
exit;

代碼片段將 output 0 1 2 3 4 5 6 7 8 9

for($player = 0; $player <= 9; $player += 2) {
    var_dump($player);
}
exit;

代碼片段將 output 0 2 4 6 8

我希望這可以幫助您更好地理解 for 循環。

您面臨的實際問題是由您使用 SQL 而不是 for 循環創建的邏輯創建的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM