问题

我有一个foreach循环,我想根据距离对结果进行排序.

 foreach ($this->items as $i => $item) {

            $latitudeFrom = 123;
            $longitudeFrom = 123;

            $theta = $longitudeFrom - $this->item->longitude;
            $dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($this->item->latitude)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($this->item->latitude)) * cos(deg2rad($theta));
            $dist = acos($dist);
            $dist = rad2deg($dist);
            $miles = $dist * 60 * 1.1515;
            $distance = $miles * 1.609344;
}

echo $distance;
 

我想用$distance对它进行排序.怎样才能做到这一点?

  最佳答案

 $latitudeFrom = 123;
$longitudeFrom = 123;

usort($this->items, function ($item1, $item2) use ($latitudeFrom, $longitudeFrom) {
    $distance1 = acos(rad2deg(sin(deg2rad($latitudeFrom)) * sin(deg2rad($item1->latitude)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($item1->latitude)) * cos(deg2rad($longitudeFrom - $item1->longitude)))) * 60 * 1.1515 * 1.609344;

    $distance2 = acos(rad2deg(sin(deg2rad($latitudeFrom)) * sin(deg2rad($item2->latitude)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($item2->latitude)) * cos(deg2rad($longitudeFrom - $item2->longitude)))) * 60 * 1.1515 * 1.609344;

    $result = 0;
    if ($distance1 < $distance2) {
        $result = -1;
    } else if ($distance1 > $distance2) {
        $result = 1;
    }

    return $result;
});
 

$this->items现在已经排序了.要反转顺序,只需切换<>.

  相同标签的其他问题

phparraysloopssorting