0

I have my location's coordinates and I want to sort the coordinates of my database from nearest to farther from my location. This is my code to take and save the coordinates:

$myXCoor = 37.9730328;
$myYCoor = 23.7533623;
$xcoor = array();
$ycoor = array();
    $result = mysqli_query($con, "SELECT * FROM `base`.`table` ;");

      while($row = mysqli_fetch_array($result, MYSQLI_BOTH))
         {

               $xcoor[] = $row['x'];
               $ycoor[] = $row['y'];

         }

I really don't how can I go on, If someone want any more details please leave a comment.

Thanks in advance

mike vorisis
  • 2,786
  • 6
  • 40
  • 74
  • 2
    Possible duplicate of [MySQL Great Circle Distance (Haversine formula)](http://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula) – cmorrissey Dec 12 '16 at 21:54

1 Answers1

1

You can do it in SQL, by adding order:

$myXCoor = 37.9730328;
$myYCoor = 23.7533623;
$xcoor = array();
$ycoor = array();
$order = "order by pow((t.x - $myXCoor),2) + pow((t.y - $myYCoor),2);";
$result = mysqli_query($con,"SELECT * FROM `base`.`table` t $order");

Or you can use usort:

$result = mysqli_query($con, "SELECT * FROM `base`.`table` ;");
$result = mysqli_fetch_all($result, MYSQL_BOTH);
usort($result, function($a,$b) use ($myXCoor,$myYCoor){
   return pow($a['x'] - $myXCoor, 2) + pow($a['y'] - $myYCoor, 2)
        > pow($b['x'] - $myXCoor, 2) + pow($b['y'] - $myYCoor, 2) ? 1 : -1;
});
2oppin
  • 1,941
  • 20
  • 33