Jump to content

Sorting results by Alphabet


TEENFRONT

Recommended Posts

Hey

 

I like to know how to sort and group results by alphabet. I have over 2800 flash games listed in my database and i want to grab the names and the id of each game, order them in alphabetical order then group them that way.

 

So the results will show like this..

 

A

A game

A game 2

A game 3

 

B

B game

B game 2

B game 3

 

C

C game

C game 2

C game 3

 

 

 

What would the query be? Cheers!

Link to comment
Share on other sites

Hi

 

SELECT * FROM tablename ORDER BY game_name ASC

 

i know how to simply order results by a column name, sorry if i wasnt very clear.

 

Once the results are sorted that way, how do i then go on to display them all seperatly, not just

 

A game

B game

C game

 

I need the results like

 

A

A game

A game 2

A game 3

 

B

B game

B game 2

B game 3

 

C

C game

C game 2

C game 3

Link to comment
Share on other sites

The way I would do it would be to break them into separate sub arrays...

 

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  $first_letter = strtoupper(substr($row['game_name'], 0, 1));
  $letters[$first_letter] = $row['game_name'];
}

ksort($letters);

echo '<pre>' . print_r($letters, true) . '</pre>';

Link to comment
Share on other sites

try

<?php
$sql = "SELECT gamename FROM games ORDER BY gamename";
$res = mysql_query($sql) or die (mysql_error()."<p>$sql</p>");

$prev = '' ;
while ($row = mysql_fetch_row($res) ) {
    $game =  $row[0];
    $initial = $game{0};
    if ($prev != $initial) {
        echo "<h3>$initial</h3>";
        $prev = $initial;
    }
    echo "$game<br/>";
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.