Frage

I have a database with index values stored in it. The data corresponds to other named data, contained elsewhere in a flat file.

I'm reading the data out of the database and matching the index value with the corresponding named data, but none of it is in any kind of order. There's not a way for me to order the data being selected out of the database, in order to have the named data be listed in order in the drop down.

Is there a way for me to order the list once I have everything matched up, before I display it to the user? Here's the code I have that does the matching.

while ($y <= $totalItemsAvail) #Loops based on the number of items needed.
{
    $itemNumberRet = getItemNames($y);
    $itemOptions.="<option value=\"$y\">".$itemNumberRet.'</option>';
    $y++;
}

I'd like to order the list here alphabetically before I actually display the options for the user.

The data looks something like this, with the item number coming from the db, and the name from the flat file:

ID          Name
1           Frank
2           Andy
3           Tom
4           Charles
5           Betty
6           Ashley
7           Ben

I'd like the list to display in alphabetical order, but also to retain the original index value stored in the $y variable.

War es hilfreich?

Lösung

Add all the options to an array first:

$itemOptions = array();
while ($y <= $totalItemsAvail) #Loops based on the number of items needed.
{
    $itemOptions[] = getItemNames($y);
    $y++;
}

Use asort() to sort them alphabetically while preserving the keys. Then use a foreach to loop through the array and display the <option>s:

asort($itemOptions);
foreach ($itemOptions as $value => $option) {
    echo sprintf('<option value="%d">%s</option>', $value, $option);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top