gpt4 book ai didi

php - 如何展平 MySQL 结果

转载 作者:行者123 更新时间:2023-11-29 02:15:55 25 4
gpt4 key购买 nike

有两个表。一张表包含球员信息,如姓名和排名。另一个表包含游戏替换信息。

输出应该是这样的:

Rank| Player Name | Period 1 position | Period 2 Position| Period 3 Position |

玩家表示例

|ID| Name | Rank    |
|1 | Fred | 10 |
|2 | Dan | 12 |
|3 | Mike | 15 |

位置表示例

|ID| Game_ID | Player_ID | Period | Position     | 
|1 | 12 | 1 | 1 | Striker Right|
|2 | 12 | 1 | 2 | Mid Center |
|3 | 12 | 2 | 1 | Striker Left |

下面是从MySQL中获取它的代码

我尝试了多种方法来转换返回的数据集。

$players_sql = "SELECT position.id as position_id,
player.rank,
player.first_name,
position.period,
position.position
FROM player
INNER JOIN position
on player.id = position.player_id
ORDER BY player.rank, position.period;";

if ($result = $mysqli->query($players_sql)) {
// printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$subs[$row["position_id"]] = [
"rank" => $row["rank"],
"first_name" => $row["first_name"],
"period" => $row["period"],
"position" => $row["position"]
];
}
mysqli_free_result($result);
}

// collapse players This works
foreach ($subs as $sub) {
$players_by_rank[$sub["rank"]] = $sub["first_name"];
}

稍后数据会以用户可以提交的形式显示。下面的代码与上面的代码不匹配。下面的代码使用静态定义的数组,其中预填充的数据不是来自数据库。它提供了一种可视化输出需要的方法。在下面的代码示例中,总共有 4 个句点进入 4 列,末尾有一个摘要列。必须有一种简单的方法来展平这些数据!

<?php
for ($sub = 1; $sub < $sub_info . length; $sub++) {
?>
<tr>
<td><?php echo $sub_info[sub] ?></td>
<td><input type = "text"
name = "p<?php echo $player; ?>"
value = "<?php echo $names[$player - 1]; ?>"
id = "p<?php echo $player; ?>" ></td>
<?php
for ($period = 1; $period < $periods + 1; $period++) {
?>
<td>
<div class="form-group">
<select onchange="calTotals(<?php echo $player . ',' . $period; ?>)"
id="<?php echo "p{$player}p{$period}"; ?>"
name="<?php echo "p{$player}p{$period}"; ?>">
<?php
$output = "";
for ($i = 0; $i < $players_on_field + 1; $i++) {
$output = "<option";
if ($i == 0) {
$output .= ' selected';
}
$output .= ">$i</option>";
echo $output;
}
?>
</select>
</div>
</td>
<?php } ?> <!-- Periods -->
<td><!-- total periods in game using JavaScript -->
<input type="text"
name="<?php echo "periods{$player}"; ?>"
id="<?php echo "periods{$player}"; ?>">
</td>
</tr>
<?php } ?> <!-- players -->

最佳答案

您可以使用join 连接表、玩家表的一个实例和三个位置(每个周期一个)

SELECT pl.rank, pl.name, 
po1.position as period_1_position,
po2.position as period_2_position,
po3.position as period_3_position from
player as pl
inner join position as po1 on pl.id = po1.player_id and po1.period=1
inner join position as po2 on pl.id = po2.player_id and po2.period=2
inner join position as po3 on pl.id = po3.player_id and po3.period=3

关于php - 如何展平 MySQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com