如何按字母顺序制作“foreach”列表项


How can I make "foreach" list items in alphabetical order

我希望按字母顺序列出项目(或在本例中为游戏标题(。

使用

php 我从 mysql databse 获取游戏,我使用 foreach 轻松列出所有游戏,但我需要它按字母顺序列出它们。

游戏.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:

$query = " 
    SELECT 
        az,
        games,
        clans,
        recruiting
    FROM `games` 
    ORDER BY games ASC
"; 
您需要

将MySQL更新为

SELECT 
    az,
    games,
    clans,
    recruiting
FROM games 
ORDER BY games ASC