php计算结果排序,php-按从数组计算出的值对数组进行排序
我從陣列中的數據庫中獲得了用戶的經緯度
我有我的經緯
現在,我要計算距離并使用該距離對數據庫中的用戶進行排序
$mylat = $_SESSION['lat'];
$mylng = $_SESSION['lng'];
$statement = $pdo->prepare("SELECT * FROM users");
$statement->execute();
$users = $statement->fetchAll();
foreach($users as $row){
$dist = 0.0;
$x1 = $mylng;
$x2 = $row['lng'];
$y1 = $mylat;
$y2 = $row['lat'];
$dist = acos(sin($x1=deg2rad($x1))*sin($x2=deg2rad($x2))+cos($x1)*cos($x2)*cos(deg2rad($y2) - deg2rad($y1)))*(6378.137);
$distn = FLOOR ( ROUND($dist,1) * 2 ) / 2 ;
}
sort($distn);
foreach ($users as $row) {
$dist = 0.0;
$x1 = $mylng;
$x2 = $row['lng'];
$y1 = $mylat;
$y2 = $row['lat'];
$dist = acos(sin($x1=deg2rad($x1))*sin($x2=deg2rad($x2))+cos($x1)*cos($x2)*cos(deg2rad($y2) - deg2rad($y1)))*(6378.137);
$distn = FLOOR ( ROUND($dist,1) * 2 ) / 2 ;
echo $row['username'];
echo $distn;
}
因此,在第一個foreach中,我計算了每個用戶到我的距離.
比我想對與我的距離后的用戶進行排序并顯示它們
那里有我的名字,也有我的距離.
user1 0.5km distance
user2 1km distance
但是我不會工作.
謝謝你的幫助 :)
解決方法:
創建一個距離函數:
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']);
}
然后,您可以通過uasort傳遞數組:
uasort ($users, 'compareDistance');
編輯:
您的程序可以被重寫:
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";
}
標簽:php,arrays,sorting,floating-point
來源: https://codeday.me/bug/20191012/1902470.html
總結
以上是生活随笔為你收集整理的php计算结果排序,php-按从数组计算出的值对数组进行排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 异常练习题_Java 异常(习
- 下一篇: z3735f android x86,英