0
我想排序一個名爲「經度」和「緯度」的變量表。我將下面的代碼用於給定的座標(45,45)。它是排序的東西,但它奇怪在我的水平列排序,而不是排.....基於經度和緯度的usort php陣列
$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) "[email protected]" }
正確答案:
$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;
}
[**請不要在新代碼**中使用'mysql_ *'函數](http://bit.ly/phpmsql)。它們不再被維護[並且被官方棄用](https://wiki.php.net/rfc/mysql_deprecation)。參見[**紅框**](http://j.mp/Te9zIL)?關於[* prepared statements *](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/mysqli) ) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 – h2ooooooo
'$ mylong和$ mylat不在distance()函數的範圍內; cmp()函數的第二行應該設置爲'$ distB',而不是'$ distA';你只從SQL中讀取一行resultset,所以這是一個基於列的數組;所以你實際上試圖對這個單獨的r的每一列進行排序esult;不是行數 –
感謝捕獲2個錯誤。但結果依然如此。我很奇怪地得到我的第一行的變量@ ____ @ – minjiera