php - 将一组数据库列添加到数组时出现问题

标签 php mysql arrays foreach

我有下表,它从我的数据库中查询用户,然后在每个用户下添加 14 个玩家。我向同一个数据库表添加了几列,我试图让这些列回显,它引发了 undefined index 错误,但我不完全确定可以在此处定义它。

这是我试图让新专栏得到回应的部分。我有 14 名玩家,因此这个数组会遍历每个用户的所有玩家。我添加了相同数量的“位置”,因此它将是玩家 1 位置 1、玩家 2 位置 2 等。

for ($playerNum = 1; $playerNum <= $totalPlayerNumbers; $playerNum++) {
    echo '<tr><td><div class="draftBorder">' . $playerNum . '</div></td>';
    foreach ($userPlayerStore as $userPlayer) {
        echo '<td><div class="draftBorder">' . $userPlayer['player' . $playerNum] . '</div></td>';

我尝试这样做,这就是为什么我收到错误...

 foreach ($userPlayerStore as $userPlayer) {
    echo '<td><div class="draftBorder">' . $userPlayer['player' . ' - ' . 'position' . $playerNum] . '</div></td>';

我还能如何格式化它,以便我可以获得显示在玩家旁边的位置。像这样:

玩家 1 - 位置 1

完整代码:

<?php $userPlayerStore = array(); ?>

<table class="draft_border_table">
    <tr>
        <th>Rnd</th>

<?php

// Output usernames as column headings
$userResults = mysqli_query($con, 'SELECT * FROM user_players ORDER BY `id`');
while($userPlayer = mysqli_fetch_array($userResults)) {
    $userPlayerStore[] = $userPlayer;
    echo '<th><div>' . $userPlayer['username'] . '</div></th>';
}

?>

    </tr>

<?php

// Output each user's player 1-14 in each row
$totalPlayerNumbers = 14;
for ($playerNum = 1; $playerNum <= $totalPlayerNumbers; $playerNum++) {
echo '<tr><td><div class="draftBorder">' . $playerNum . '</div></td>';
foreach ($userPlayerStore as $userPlayer) {
     if (empty($userPlayer['player'.$playerNum])){
       $extra_class = 'emptycell';
    }else{
       $extra_class = 'filledcell';
    }
    echo '<td class="draft_table_td">' . $userPlayer['player' . $playerNum] . '</td>';
}
echo '</tr>';
}

?>

</table>

最佳答案

$userPlayer 变量反射(reflect)了数据库表中的每条记录,该数组中的每个索引都是列名称。下面的代码应该对您有帮助:

// Output each user's player 1-14 in each row
$totalPlayerNumbers = 14;
for ($playerNum = 1; $playerNum <= $totalPlayerNumbers; $playerNum++) {

    // Start the player row
    echo '<tr><td><div class="draftBorder">' . $playerNum . '</div></td>';

    foreach ($userPlayerStore as $userPlayer) {

        // Retrieve extra class name? Did you mean to use this?
        $extraClass = empty($userPlayer['player' . $playerNum]) ? 'emptycell' : 'filledcell';

        // Output player name and position
        $playerName = $userPlayer['player' . $playerNum];
        $playerPosition = $userPlayer['position' . $playerNum];
        echo '<td class="draft_table_td">' . $playerName . ' - ' . $playerPosition . '</td>';
    }

    // End the player row
    echo '</tr>';
}

关于php - 将一组数据库列添加到数组时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32421942/

相关文章:

php - 使用 redis 和 php 发送电子邮件

android - 我现在可以使用 Firebase 吗?

c - 对数字数组求和但在运行时收到错误

c# 数组或集合

php - 具有多个数据库的单例

php - Git POST webhook shell_exec

mysql - SQL - 聚合除组之外的所有内容

mysql - 如何在 MySQL 中返回数据透视表输出?

arrays - vlookup 和绝对引用以及 lastrow VBA 的问题

php - 如何在 Laravel 中将数组对象和数据添加到 JSON