我正在创建一个显示玩家详细信息的页面,并将信息拉得很好。我还有一个连接表,从另一个表中提取单个记录的国籍罚款,所以连接不是问题。
但现在完全坚持如何循环已经循环的数据。
在我的players.php类中,我有一个函数可以提取我需要的所有信息,并且可以在前端显示。
function getById($id)
{
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *, nationalities.nationality FROM players
LEFT JOIN nationalities ON players.nationality = nationalities.id
WHERE players.id = :id";
$st = $conn->prepare($sql);
$st->bindValue(":id", $id, PDO::PARAM_INT);
$st->execute();
$row = $st->fetch();
$conn = null;
if ($row) return new Players($row);
}
function getList($numRows = 1000000, $order = "lastname DESC")
{
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql = "SELECT SQL_CALC_FOUND_ROWS *, lastname AS lastname FROM players
ORDER BY " . ($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ($row = $st->fetch())
{
$player = new Players($row);
$list[] = $player;
}
//Now get the total number of players that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query($sql)->fetch();
$conn = null;
return (array("results" => $list, "totalRows" => $totalRows[0]));
}
我的挑战是玩家可以有多个位置,而不仅仅是1个显示?我如何实现这一点我在尝试使用SQL后循环时尝试过但它似乎并没有起作用我接近它的方式。我的表是:
**players**
id, firstname, lastname ...
**positions**
id, position
**player_positions**
player_id, position_id
使用以下数据集查询:
SELECT positions.position, players.firstname, players.lastname
FROM positions
LEFT JOIN player_positions ON positions.id = player_positions.position_id
LEFT JOIN players ON player_positions.players_id = players.id
WHERE players_id = :id
position, firstname, lastname
RWB, Lewis, Robinson
CB, Lewis, Robinson
我的第一个循环是通过玩家并检索数据很好,但现在我需要它在这个数据集上循环数据循环并将其存储为位置,然后能够在前端显示它:(
任何有关做这种事情的帮助或指示都会很棒
答案 0 :(得分:0)
我会按玩家分组位置,然后使用双循环显示玩家位置。
function getList($numRows = 1000000, $order = "lastname DESC")
{
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql = "SELECT SQL_CALC_FOUND_ROWS *, lastname AS lastname, id AS id FROM players
ORDER BY " . ($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ($row = $st->fetch())
{
$id = $row[2];
$player = new Players($row);
if(!isset($list[$id])) list[$id] = array();
$list[$id][] = $player;
}
//Now get the total number of players that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query($sql)->fetch();
$conn = null;
return (array("results" => $list, "totalRows" => $totalRows[0]));
}
//Used like this (just an example for the loops):
$list = getList();
foreach($list as $id => $positions) {
echo $positions[0]->playerName."<br>";
foreach($positions as $player) {
//Output
echo print_r($player, true)."<br>";
}
}