How to alphabetical sort mysql query field variable in PHP?

Today I was working on a code and find some difficulty while doing it. So I thought, I should share this with all of you.

Actually, I want to alphabetical sort MySQL query filed value variable.

Let’s start it with a code –

 $sql= mysql_query("Select DISTINCT(`Supervisor ID`) from `list` ");

In the above query, I am selecting unique supervisor id from table list. Actually, I need names who are Supervisors and I have only supervisor ids.

In below code, I got the ids of Supervisors I again fire the query to find the Name who are Supervisors.

Now, $username[0] field contains the names of all Supervisors. But I was stuck, how to sort this $username[0] variable that contains all names.

So, i sort name into a new array $uname[] .

while($row = mysql_fetch_array($sql))
{   
     $id = $row['Supervisor ID'];
     $query = "SELECT `Name` from `list` WHERE `ID` = '$id'  ";
     $name = mysql_query($query);

     $username = mysql_fetch_array($name);
/* Sort name in to an new array */
     $uname[] = $username['0'];
}

Now, I used the sort() function to sort the array.

$user_names = sort($uname);

Then, I created all the options values like this –

foreach($uname as $name) {
echo $name;
}

This will print all names who are Supervisors in alphabetical order. The main work was here to sort name into a new array and then sort names.

2 Comments

Leave a Reply