Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Order in alphabetical order

Tags:

php

list

I'm trying to make a simple alphabetical list to order items in my database. The thing I can't figure out is how to actually list it.

I would like it to be the same format as you have on miniclip.com

Here's an image

alt text

I looked around, but couldnt find an answer really.

(I would like it to finish even at the end of each vertical column, except the last one for sure)

Any help would be welcome!

like image 280
Alex Cane Avatar asked Dec 09 '22 12:12

Alex Cane


2 Answers

In MySQL:

SELECT * FROM table ORDER BY name ASC

In PHP:

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
like image 92
Webnet Avatar answered Dec 26 '22 14:12

Webnet


Assuming that your result set already is sorted by using the ORDER BY clause, to group the results by their first character you just need to remember the first character of the previous entry and print out the first character of the current entry if they are different. So:

$prevLabel = null;
while ($row = mysql_fetch_assoc($result)) {
    $currLabel = strtoupper(substr($row['name'], 0, 1));
    if ($currLabel !== $prevLabel) {
        echo $currLabel;
        $prevLabel = $currLabel;
    }
    echo $row['name'];
}

This will print the first character as a label for each group that’s members have the same first character.

like image 30
Gumbo Avatar answered Dec 26 '22 15:12

Gumbo