Sort Arrary Starting with given value

Hello!

My goal is to sort an array starting with a given value.

For example, I have three employees: Smith, Jones, Taylor. They are stored in an array created from my database. I am populating a drop down menu with these names. I want the current user’s name to be at the top of the drop down list. This way by default their name is selected. If they would like to select another employee they have to click the list and choose. Can someone please provide the basic code to sort the array?

Thanks!

[php]$array = array(‘Joe’,‘Aaron’,‘Bobby’,‘Gary’);
$thisPersonKey = array_search($_SESSION[‘name’],$array);
$people = array();
$people[] = $array[$thisPersonKey];
unset($array[$thisPersonKey]);
$people = array_merge($people,$array);
[/php]

That should do the trick. Not tested though, not got testing environment available to me at the moment, but let me know.

Thank you so much for the reply. I am a little deeper in it now though. Here is what I have, but can’t seem to get the code to work. I would actually like the employee name to show up at the top of the drop down and in the list of employees.

while($row1 = mysql_fetch_array($result1)){
$data[]=$row1;
}
$beginning = array(array(“LastName”=>$LastName, “Employee_ID”=>$Employee_ID));
$result = array_merge($beginning, $data);

                                       echo "<select>";
						$c=count($result);
						for ( $i=0; $i < $c; $i++)
						{
   						echo "<option>";
   						$result[$i]['LastName'];
   						echo "</option>";
						}  
					echo "</select>";

Well, normally, you would have the names sorted alphabetically so the user can find who they are looking for faster and just have the current selected one be highlighted and showing selected. In this way, they can just go up or down alphabetically which is so much easier…

But, if you still want to do it your way, you would need to make the first OPTION be outside your loop.
Then, you would parse thru the rest and just skip the one that is currently selected. In this way the current is at the top and the rest follow…

Not sure, but something like this:
[php]

// Force first option to be current name ($beginningName is the variable I made up)
echo “”;
echo “$beginningName”;

// Put rest of names in options…
while($row1 = mysql_fetch_array($result1)){
if($row1[‘LastName’] != $beginningName)
echo “” . $row1[‘LastName’] . “”;
}

echo “”;
[/php]
Something simple like that should work for you…

Sponsor our Newsletter | Privacy Policy | Terms of Service