Skip to content
Advertisement

Alphabetic ordering for names

I have been struggling with this for almost 2 days now and i just can not get it to work myself. Basically my goal is to make a list from A to Z, with values from a database. Example:

JavaScript

Now my php code looks like this:

JavaScript

Now, it does work when i put strings inside the array and remove the foreach loop on top: $card = array("Betty", "Britney", "Adam", "Antony");

And my function (basically a query exector), looks like this:

JavaScript

I dont think there is anything wrong with the function itself but with the php code, i hope someone has the answer i have been looking for.

Advertisement

Answer

One solution could be to use PDO::FETCH_GROUP together with LEFT() to select the first letter in MySQL as first column of the result and group by this first column:

JavaScript

Outputs:

JavaScript

Or just group it yourself in PHP:

JavaScript

Output should be exactly the same as above (just without the print_r() part).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement