ineedhelpbigtime Posted August 2, 2009 Share Posted August 2, 2009 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. Link to comment https://forums.phpfreaks.com/topic/168537-solved-how-do-i-filter-an-fetched-array-based-on-a-calculation-within-the-while-loop/ Share on other sites More sharing options...
Daniel0 Posted August 2, 2009 Share Posted August 2, 2009 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). Link to comment https://forums.phpfreaks.com/topic/168537-solved-how-do-i-filter-an-fetched-array-based-on-a-calculation-within-the-while-loop/#findComment-889082 Share on other sites More sharing options...
ineedhelpbigtime Posted August 2, 2009 Author Share Posted August 2, 2009 That is such a beautiful solution. I should remember that mySQL can compute too . Thank you very much. Link to comment https://forums.phpfreaks.com/topic/168537-solved-how-do-i-filter-an-fetched-array-based-on-a-calculation-within-the-while-loop/#findComment-889127 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.