I have the lat and lng from a user from the database in an array and I have my lat and lng
Now I want to calculate the distance and sort the users from my database with
Create a distance function:
function getDistance ($lat, $lon)
{
global $mylng, $mylat;
$x1 = deg2rad($mylng);
$x2 = deg2rad($lon);
$y1 = deg2rad($mylat);
$y2 = deg2rad($lat);
$dist = acos(sin($x1)*sin($x2)+cos($x1)*cos($x2)*cos($y2 - $y1))*(6378.137);
return $dist;
}
Create a comparison function:
function compareDistance ($user1, $user2)
{
return getDistance ($user1['lat'], $user1['lng']) - getDistance ($user2['lat'], $user2['lng']);
}
Then you can pass your array through uasort
:
uasort ($users, 'compareDistance');
See http://php.net/manual/en/function.uasort.php for more information.
EDIT:
Your program could be rewritten:
function getDistance ($lat, $lon)
{
global $mylng, $mylat;
$x1 = deg2rad($mylng);
$x2 = deg2rad($lon);
$y1 = deg2rad($mylat);
$y2 = deg2rad($lat);
$dist = acos(sin($x1)*sin($x2)+cos($x1)*cos($x2)*cos($y2 - $y1))*(6378.137);
return $dist;
}
function compareDistance ($user1, $user2)
{
return getDistance ($user1['lat'], $user1['lng']) - getDistance ($user2['lat'], $user2['lng']);
}
$mylat = $_SESSION['lat'];
$mylng = $_SESSION['lng'];
$statement = $pdo->prepare("SELECT * FROM users");
$statement->execute();
$users = $statement->fetchAll();
uasort ($users, 'compareDistance');
foreach ($users as $row) {
$dist = getDistance ($row['lat'], $row['lng']);
$distn = floor(round($dist,1) * 2) / 2 ;
echo $row['username']. ": " . $distn . "km distance";
}