Posts Tagged ‘array’

Sorting Specific Array

// October 13th, 2008 // No Comments » // PHP

I needed to dynamically load a group of options from the database. The thing was that these were not organised alphabetically; instead they were ordered in platinum, gold, silver, bronze format. This posed a little bit of a problem. The way around it was seeting up an array with the correct order of options. Then query the DB and bring back the results. Looping through these results and getting the array key of the organised array. A new array created stores the options from the db, and is sorted on its keys with ksort.

$orderedarr = array(
0 => “platinum”,
1 => “gold”,
2 => “silver”,
3 => “bronze”);

$rsCustomerStatus = $db->query(“SELECT DISTINCT ProspectStatus
FROM tblFleetCustomer
WHERE (ProspectStatus IS NOT NULL) AND (ProspectStatus <> ”) ORDER BY ProspectStatus DESC”,1);

$displayarr = array();

foreach($rsCustomerStatus as $rowStatus)
//put the value in the correct position in array
$valarr = array_keys($orderedarr, strtolower($rowStatus["ProspectStatus"]));
$displayarr[$valarr[0]] = $rowStatus["ProspectStatus"];


//display array in correct order
foreach($displayarr as $val)
echo “<option value=\””. $val .”\”>”. htmlentities(ucwords(strtolower($val))) . “</option>\r\n”;