Jump to content

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


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).

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.