Saturday, April 18, 2009

PHP Sorting Parallel Arrays

This weekend I put the finishing touches on a zip code search program for Hubalub private tutors. The goal was for parents to be able to find all tutors within a given radius of a given zip code. Well, after brushing up on some of the fun non-Euclidean geometry necessary to calculate distance on a sphere (check out the Haversine formula at wikepedia), I found myself dealing with the following dilemna. I had about 8 parallel arrays representing the username, cityname and other personal details of the members who were within the radius of a given zip code.

Below is simplified snapshot of the arrays in question.
$userNames =array();
$userAvatars = array();
$distances = array();

Naturally, I wanted to display the tutors by distance in descending order so that you'd see the closest tutor first. No problem right, just use one of PHP's handy sorting functions like ksort() or krsort(), but if you ksort() an array, you've lost the whole 'parallelism' of the arrays! After toying with different possible solutions, the easiest one seemed to be to create a hashmap in which the distances served as keys and then concatenated all the user details into 1 long comma separated string (which could be exploded later). This allowed me to ksort() the array based on the key which was the distance! And Bam! user data is now in descending order based on distance. The only thing to be careful of is that if two distances were the same (ie duplicate keys) you'd end up with an array of buckets that you'd to loop over.