Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sort an array by an array

Status
Not open for further replies.

Moooink

Technical User
Feb 22, 2002
48
US
here's my issue. i have an array from a mysql db.

name | employee | email
name2 | director | email2
name3 | assistant director| email3

and then i have an array with positions in it like the following:
$staffsort = array("director", "assistant-director", "employee");

how do i sort the result array from the mysql query to be in the order of the staff order array? i've looked all over, can't seem to find the answers.
thanks
Moooink
 
In general, you could perform a sieve operation:

$sorted_staff = array();
foreach ($staffsort as $position)
{
foreach ($staffdata as $staff_member)
{
if ($staff_member['position'] = $position)
{
$sorted_staff[] = $staff_member;
}
}
}

It's brute force, but it should work.


I recommend, however, that you make MySQL do more of the work for you.

Something like:

foreach ($staffsort as $position)
{
mysql_query (&quot;SELECT * FROM <table> WHERE <columname> = '$position'&quot;);

...process return...
}


You could make MySQL do more of the work by using a lookup table. Instead of storing the textual name of the position-level in the table of staff data, create another table which looks something like:

table position_data:
id title
100 director
75 assistant director
25 employee

And in your staff table, just store the ID of the position from this table. This way, you can get the records in exactly the order you want by issuing the query:

SELECT * FROM table, position_data WHERE table.position_id = position_data.id ORDER BY position_level DESC, lastname

This way, you don't have to pull out all the data into an array and process it. Just fetch each row and output. The database is more correctly normalized this way, too. Want the best answers? Ask the best questions: TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top