PHP mysqli_fetch_array选择最小值

时间:2017-04-11 02:18:46

标签: php mysql geolocation

嘿伙计们,谢谢你们的帮助。 我要做的是使用用户的纬度和经度,并将其与我在数据库中保存的城市的纬度和经度进行比较。我现在的代码有效,但问题是在半径30英里范围内可能有多行。看看我的代码,如果可以,请帮助我。

<?php function distance($lat1, $lon1, $lat2, $lon2) {

    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lon1 *= $pi80;
    $lat2 *= $pi80;
    $lon2 *= $pi80;

    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlon = $lon2 - $lon1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;

    //echo '<br/>'.$km;
    $km = $km * 0.621371;
    return $km;
 }
    include_once("dbconnect.php");
    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }
    $grabCities = "SELECT * FROM cities";
    $result = $mysqli->query($grabCities);
    while($row = mysqli_fetch_array($result)){ 
    $distance = distance(41.08866717,-81.4780426,$row['lat'],$row['longitude']);
    if ($distance < 30){
        echo $myCity = $row['City'] . "<BR>";
    }

    }
    $mysqli->close();
?>

2 个答案:

答案 0 :(得分:2)

您可以使用MYSQL执行此操作,返回1个结果,这是您想要的结果。

sprintf('
    SELECT
        *,
        (((acos(sin((%1$d*pi()/180)) * 
            sin((`lat`*pi()/180))+cos((%1$d*pi()/180)) * 
            cos((`lat`*pi()/180))*cos(((%2$d-`longitude`) * 
            pi()/180))))*180/pi())
        ) as distance
        FROM `cities` 
    ORDER BY
        distance ASC
    LIMIT 1
    ',
    $latitude,
    $longitude
);

答案 1 :(得分:0)

这样的东西?未经测试。

$smallestDistance = null;

while($row = mysqli_fetch_array($result)){ 
    $distance = distance(41.08866717,-81.4780426,$row['lat'],$row['longitude']);
    if ($distance < $smallestDistance){
        $myCity = $row['City'];
    }
    $smallestDistance = $distance;
}

echo $myCity;