0
我期望按字母順序列出項目(或本例中爲遊戲標題)。我如何按字母順序製作「foreach」列表項目
使用PHP我從一個MySQL數據庫獲取遊戲,我使用foreach輕鬆列出所有遊戲,但我需要它按字母順序列出它們。
games.php
<table style="width:100%;" class="hover">
<th style="width:5%;">A-Z</th>
<th style="width:70%;">Games</th>
<th style="width:10%;">Clans</th>
<th style="width:10%;">Recruiting</th>
<tr>
<td></td>
<td>None Specified</td>
<td></td>
<td></td>
</tr>
<?php
$query = "
SELECT
az,
games,
clans,
recruiting
FROM games
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row): ?>
<tr>
<td><?php echo $row['az']; ?></td>
<td><a href="/games/"><?php echo $row['games']; ?></a></td>
<td><?php echo $row['clans']; ?></td>
<td><?php echo $row['recruiting']; ?></td>
</tr>
<?php endforeach; ?>
<tr>
<th style="width:5%;">A-Z</th>
<th style="width:70%;">Games</th>
<th style="width:10%;">Clans</th>
<th style="width:10%;">Recruiting</th>
</tr>
</table>
,而不是試圖要挾循環到不同的排序順序,你應該將'ORDER BY Games'應用到SQL(o r無論哪一列是所需的排序) –
如其他答案和評論中所述,編輯您的SQL。但是,如果出於某種原因,您想從數據庫獲取數據庫後以不同的方式對數據庫結果進行排序。用這個要求編輯你的問題。 – nakashu