我正在通过php打印棒球队阵容。我想为丢失的玩家6(或任何缺失的位置)打印占位符
所以如果玩家1 - >播放器5是OK打印,NO播放器#6打印占位符,播放器7 - >播放器9可以打印。我试图简化代码。我已经尝试过解决这个问题但我一直陷入困境。
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>";
}
}
}
答案 0 :(得分:0)
怎么样:
# 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 ...
}
}
答案 1 :(得分:0)
我认为你正在创建一个数组,其中所有数字元素都被填充(即你总是有1到15)并且你的错误在于 if($ rot [$ i] == $ i){
从数据库填充数组时,添加以下行:
$playertoid = array_flip($pos); # pos is the player number array?
即。
while ( ($rot[$x], $pos[$x], $jn[$x])= $r->fetch_row() ) {
$x++;
}
$playertoid = array_flip($pos);
现在您已经创建了一个反向查找表,其中索引是玩家编号。
替换
if($rot[$i] == $i) {
符合:
if (isset($playertoid[$i])) {