sort array by value that is calculated from the array

前端 未结 1 1066
日久生厌
日久生厌 2021-01-24 16:29

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

相关标签:
1条回答
  • 2021-01-24 16:59

    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";
    }
    
    0 讨论(0)
提交回复
热议问题