Main Content

PHP - setting sort order with an associative array

Archive - Originally posted on "The Horse's Mouth" - 2006-02-13 00:39:38 - Graham Ellis

I was updating one of our web site scripts a few hours back, and I wanted to sort the rows of an HTML table generated by the PHP from a directory listing. Problem was that I was making the table up using concatanation (.=) operators in a single string.

First solution - put all the table rows into an array and sort the array. Alas, this solution was ugly because the usort routine needed to sort the list some ugly code to unpick the table rows that I had just carefully created.

Second solution - and very neat though I say it myself - was to put the table rows into an associative array and set up the keys of the array to be the sort key. All I need to then is a ksort to get the rows in order, and an implode to join up the values in the table since implode ignores the keys if its input is associative

Code:


$fill = array();
$dh = opendir($source);
while ($name = readdir($dh)) {
/* code to work out the table row ... */
$fill[$name] = /* Nasty per-line code! */
}
ksort($fill);
$fillit = implode("",$fill);