Jump to content

[SOLVED] How do i filter an fetched array based on a calculation within the while loop?


ineedhelpbigtime

Recommended Posts

I have created a piece of code to return the 'in game' distance of other alliance players on a RTS online game.

 

To use this function a player enters the co-ordinates of a town, i.e X=339 and Y=224, on a previous page. These values are posted to the nearbyplayers.php page (the page the code below relates to) and assigned as $a and $b.

 

I have a DB table called 'towns' containing the other players town co-ordinates and details which are all fetched in a mysql_query (select).

$towns = mysql_query ("select * from towns");
$othertrows = mysql_fetch_array($towns);

 

I then perform the following code.

 

while($othertrows = mysql_fetch_array($towns)) {
//Assign a players co-ords to variables.
$oX = $othertrows['X'];
$oY = $othertrows['Y'];

//work out the distances
$DisX = $oX - $a;
$DisY = $oY - $b;
// if either of the distances are negative, swap the figures to get a positive, this makes no difference to the end result as far as i can see.
if ($DisX < 0)
{$DisX = $a - $oX;}
if ($DisY < 0)
{$DisY = $b - $oY;}
// Calculate distance using pythagoras.
$distance = round(sqrt(($DisX*$DisX)+($DisY*$DisY)),1);
// Output results line by line to a table.
echo "<tr><td>$othertrows[playername]</td><td>$othertrows[townname]</td><td>$othertrows[X]</td><td>$othertrows[Y]</td><td>$distance</td><td>$othertrows[status]</td><td>$othertrows[towndesc]</td></tr>";}
echo "</table>"; }

 

This code outputs the distance's correctly. However, i would like to order the results by distance, and seeing as the distance calculation occurs in the while loop, i am unsure how i will be able to do this.

 

Many thanks for your help, it is always invaluable.

Something like this should do:

 

SELECT town_id, name, ROUND(SQRT(POW(location_x - 339, 2)+POW(location_y - 224, 2)), 1) AS distance FROM towns ORDER BY distance DESC, name;

 

That will get the distance of all the towns from the point (339, 224).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.