我正在用Geotools软件包开发一个应用程序,我有一个问题:
public function prodcercanos()
{
$cercanos = User::with('municipio')->with('productos')->get();
$coordA = Geotools::coordinate([44.4578589, 2.2951061999999998]);
foreach ($cercanos as $p) {
$coordB = Geotools::coordinate([$p->municipio->latitud,$p->municipio->longitud]);
$distance = Geotools::distance()->setFrom($coordA)->setTo($coordB);
echo $p->id;
echo "<p>";
echo $distance->in('km')->haversine();
echo "</p>";
}
}这段代码返回foreach中各点之间的距离,但我需要用这个距离对foreach进行排序,我不知道如何做到这一点。
有人能帮我吗?
发布于 2015-05-21 14:05:40
在foreach循环中,将其全部放在一个数组中,而不是遍历该数组。您可以使用距离作为键,使用HTML输出作为值。可以在数组上使用克索德函数按键对其进行排序。
public function prodcercanos()
{
$cercanos = User::with('municipio')->with('productos')->get();
$coordA = Geotools::coordinate([44.4578589, 2.2951061999999998]);
$output = [];
foreach ($cercanos as $p) {
$coordB = Geotools::coordinate([$p->municipio->latitud,$p->municipio->longitud]);
$distance = Geotools::distance()->setFrom($coordA)->setTo($coordB);
$dis = $distance->in('km')->haversine();
$output[$dis] = $p->id . "<p>$dis</p>";
}
ksort($output);
foreach ($output as $line) {
echo $line;
}
}发布于 2015-05-21 14:04:09
在PHP中使用sort()函数。要使用的语法:sort(array,sortingtype);
使用以下链接获取更多信息:sort.asp
https://stackoverflow.com/questions/30375892
复制相似问题