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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值