0

我正在尝试对具有名为“经度”和“纬度”的变量的表进行排序。我针对给定坐标 (45,45) 使用下面的代码。它正在对某些东西进行排序,但奇怪的是它在我的列中水平排序,而不是行......

$mylat = 45;
$mylong= 45;

$res = mysql_query("SELECT * FROM account");
$users = mysql_fetch_row($res);

function distance($lon1, $lat1) { 
    $theta = $lon1 - $mylong; 
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($mylat)) +  cos(deg2rad($lat1)) * cos(deg2rad($mylat)) * cos(deg2rad($theta)); 
    $dist = acos($dist); 
    $dist = rad2deg($dist);
    return $dist;
}

function cmp($a, $b) {
    $distA = distance($a['longitude'],$a['latitude']);
    $distB = distance($b['longitude'],$b['latitude']);
    if($distA == $distB) {
    return 0;
}
    return ($distA > $distB) ? -1 : 1;
}

usort($users, "cmp");

当我 var_dump 时,这是结果(这是表格第一行的内容!!)快把我逼疯了!!:

 { [0]=> string(2) "30" [1]=> string(3) "999" [2]=> string(14) "20131018111824" [3]=> string(2) "30" [4]=> string(1) "m" [5]=> string(8) "xxxxxxxx" [6]=> string(8) "xxxxxxxx" [7]=> string(2) "45" [8]=> string(12) "xxx@gmail.com" }

正确答案:

$res = mysql_query("SELECT * FROM account");
   while( $row = mysql_fetch_assoc( $res)){
      $users[] = $row; // Inside while loop
   }

function distance($lon1, $lat1) { 
    GLOBAL $mylat;
    GLOBAL $mylong;
    $theta = $lon1 - $mylong; 
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($mylat)) +  cos(deg2rad($lat1)) * cos(deg2rad($mylat)) * cos(deg2rad($theta)); 
    $dist = acos($dist); 
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515; 
    return $miles;
}
4

1 回答 1

0

您的距离函数看不到$mylat,$mylong变量。(您应该global $mylat, $mylong;在函数体的第一行之前添加一个。

于 2013-10-18T10:43:05.653 回答