我正在开发一个应用程序与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
进行排序,我不知道如何做到这一点。
有人能帮我吗?
在foreach循环中,将所有内容放入数组中,然后遍历该数组。您可以使用距离作为键,并使用HTML输出作为值。你可以在数组上使用ksort函数来按键排序。
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;
}
}
使用PHP中的sort()
函数。使用的语法:sort(array,sortingtype);
使用以下链接获取更多信息:http://www.w3schools.com/php/func_array_sort.asp