Forum Moderators: coopster

Message Too Old, No Replies

Fill then sort array from PHP mySQL Query

         

devitnow

2:31 pm on Feb 24, 2005 (gmt 0)

10+ Year Member



Hi Everyone,

As I'm sure you can see from my code below, I'm an array newbie. What I'm trying to do is compute the nearest distance of two zip codes. If I were just matching two zip codes, this would be no problem, but I need to compare the customer's zip code against a list of merchant zip codes stored in the database.

My idea was that during the loop, I could calculate the zip code distance, stuff it into a new array, then sort for the lowest value. But, because I have so little experience with arrays, this is proving to be very difficult for me.

Here's the part of the code where I'm lost:

$findLocations = mysql_query("SELECT latitude, longitude FROM locations");
while ($loop_findLocations = mysql_fetch_array($findLocations)) {
$latitude = $loop_findLocations["latitude"];
$longitude = $loop_findLocations["longitude"];
$yarddistance = distance($latitude, $longitude, $cutomerlat, $cutomerlong, "m");
$nearest_distance = array($yarddistance);
sort($nearest_distance);
print_r($nearest_distance); // print array to see what's happening
}
echo '<br> Best Yard:'. $nearest_distance;

The current output of the script is this:

Array ( [0] => 1956.0688881835 ) Array ( [0] => 1998.9853287785 ) Array ( [0] => 1839.565611694 ) Array ( [0] => 1900.3659881069 ) Array ( [0] => 59.368599722285 ) Array ( [0] => 197.68427334405 )
Best Yard:Array

Besides not understanding the basics of arrays, something I'm trying to correct, where am I going wrong?

thank you.

ironik

9:37 pm on Feb 24, 2005 (gmt 0)

10+ Year Member



Your populating $nearest_distance with sub-arrays, if you change the code like this it should work:

[example]
$nearest_distance = array();
$findLocations = mysql_query("SELECT latitude, longitude FROM locations");
while ($loop_findLocations = mysql_fetch_array($findLocations)) {
$latitude = $loop_findLocations["latitude"];
$longitude = $loop_findLocations["longitude"];
$yarddistance = distance($latitude, $longitude, $cutomerlat, $cutomerlong, "m");
$nearest_distance[] = $yarddistance;
}
sort($nearest_distance);
print_r($nearest_distance); // print array
echo '<br> Best Yard:'. $nearest_distance[0];
[/example]

Without testing, that should print the first element from the array after it is sorted (which should be the lowest number).

I've removed the sort and print_r out of the loop, as you want to do your sorting after the array is populated with data.

Hope this helps :)

devitnow

9:44 pm on Feb 24, 2005 (gmt 0)

10+ Year Member



yeap, that worked - thanks a ton!