How to Sort a Multi-Dimensional Array
(Page 1 of 4 )
Yes, the title is a mouthful. But unfortunately with classic ASP, trying to make sense of an unsorted array is much worse. It is quite often the case, especially when retrieving data from a database, that it may end up in an array which is not ordered perfectly, perhaps due to incorrect data type settings. And of course, ASP would provide us with no intrinsic array sorting mechanisms. This article will explain how to take the array of that data, and hand it off to a function to sort it based on whichever dimension you specify, also with the ability to handle various data types.
Introduction
I don't especially enjoy sorting laundry. It's boring, and feels somewhat pointless, but at least it's easy to do. It would not be nearly as easy for a web application to sort your laundry. Though it would be far more willing to do work, it just wouldn't understand what laundry is, why it needs to be sorted, and in what order. And as it turns out, if you're using ASP, an array of any type may as well be laundry, because there's no intrinsic way to sort arrays, no matter how simple it may be.
The first time I ran across this issue was with an array of dates. The dates were for events, and all the event information was stored in a database. Normally it wouldn't be an issue retrieving the dates in a properly sorted result set; I could just specify an ORDER BY clause in the SQL statement, which I tried. But the problem here was that the table the events were in was exceedingly normalized. Instead of having separate fields for the date, event title, and other attributes, I had one field called 'content' and another field to identify the type of content it is. That means that every field, every date, every time was stored as the generic type of text.
So I would go about retrieving the data, trying to order it properly, and it worked well for the most part. But when you treat a date as text, funny things happen. Though you and I know that October is farther away than February, a database holding the values as text does not. You see, October would be '10-01-2004', and February would be '02-01-2004', which looks like a larger text value than the first, and when you dump the results into the array you get one funky calendar.
As you can guess, people did not derive extreme pleasure in the application telling them that events in October were now happening at the beginning of the year, so something needed to be done. I had dumped all the data for the events into a multi-dimensional array, so the first thing I did was consult some ASP documentation on how to sort arrays. Much to my chagrin there was nothing to be found. So, I was forced to go it alone, hack out some method to do my sorting, the results of which I share with you today.
Next: A Quick Explanation of the Multi-Dimensional Array Function >>
More ASP Articles
More By Justin Cook