我正在通过php打印棒球队阵容。我想为缺少的Player 6(或任何缺少的位置)打印一个占位符

因此,如果播放器1->播放器5是OK打印,则没有播放器#6打印占位符,播放器7->播放器9是OK打印。我试图简化代码。我试图以各种方式解决此问题,但我一直陷于困境。

CODE:

$rot        = array();
$pos        = array();
$jn             = array();

$x = 1;
// loads up the arrays from the db
while ( $rot[$x], $pos[$x], $jn[$x])= $r->fetch_row() ) {
$x++;
}

// counts the actual number of players in linuep
// used for validation and error display
$num_players = mysqli_num_rows($r);

// controls the lineup position
for ($i = 1; $i <= 15; $i++){
    if($rot[$i] == $i) {
    //prints player
$lineup .= "<div data-fp='" . $pos[$i] . "'>" .$jn[$i]. "</div>";
    } else {
        // prints place holder
        $text = "This Position needs to be filled before the next game.";
        $lineup .= "<div id='pid' data-rel='".$text."' data-fp='' data-pid='' data-jn='' title=''>x</div>";
    }
}


我也尝试过遍历数组rot []以找到匹配的位置并打印该行,但实际上它会重复打印该持有人。

// controls the lineup position
for ($x = 1; $x <= 15; $x++){

for ($i = 1; $i <= ($num_players+1); $i++) {
  if ($x == $i) {
       //prints player
        $lineup .= "<div data-fp='" . $pos[$i] . "'>" .$jn[$i]. "</div>";
    } else {
        // prints place holder
        $text = "This Position needs to be filled before the next game.";
        $lineup .= "<div id='pid' data-rel='".$text."' data-fp='' data-pid='' data-jn='' title=''>x</div>";
    }
  }
}

最佳答案

关于什么:

# index all players by position while taking them from the database

$players = array();
while ( $row = $r->fetch_row() ) {
    list($rot, $pos, $jn) = $row;
    $players[$pos] = compact(array('rot', $pos, $jn);
}

...

# line-up players
for ($pos = 1; $pos <= 15; $pos++)
{
    $playerExists = isset($players[$pos]);

    if ($playerExists)
    {
       # do this ...
    }
    else
    {
       # do that ...
    }
}

09-10 00:52
查看更多