基于经度和纬度的usort php数组

时间:2013-10-18 10:32:20

标签: php sorting

我正在尝试对具有名为“longitude”和“latitude”的变量的表进行排序。我使用下面的代码对应给定的坐标(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;
}

1 个答案:

答案 0 :(得分:0)

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