PHP – 输出结果以while()循环的升序排列

我需要根据循环内部的计算显示结果.循环的结果应该是$distance的升序.

    $sql = "SELECT DISTINCT * FROM cinemas WHERE city='$city'";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) {

        while($row = $result->fetch_assoc()) {



    $lat1 = $_GET['lat'];
    $lon1= $_GET['lon'];
    $lat2 = $row['latitude'];
    $lon2 = $row['longitude'];

    //starting calculating the distance

      $theta = $lon1 - $lon2;
      $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
      $dist = acos($dist);
      $dist = rad2deg($dist);
      $miles = $dist * 60 * 1.1515;
      $unit = $miles * 1.609344;

    $distance = substr($unit,0,4);
echo $row['cinemaname'].$distance;

}}

如何根据$distance以升序显示结果?

它显示为:

cinema name 20 km
cinema name 5 km
cinema name 30 km
cinema name 3 km

我需要展示:

cinema name 3 km
cinema name 5 km
cinema name 20 km
cinema name 30 km

最佳答案 将while中的return保存在数组中,如下所示:

$cinema[$i]['cinemaname'] = $row['cinemaname'];
$cinema[$i]['distance'] = $distance;

并且在此之后制作:

function sortByOrder($a, $b) {
    return $a['distance'] - $b['distance'];
}

usort($cinema, 'sortByOrder');

现在你有订单:)

这是你现在的代码:

$sql = "SELECT DISTINCT * FROM cinemas WHERE city='$city'";

$result = $conn->query($sql);
$cinema = array();
$i = 0;
if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
       $lat1 = $_GET['lat'];
       $lon1= $_GET['lon'];
       $lat2 = $row['latitude'];
       $lon2 = $row['longitude'];

       //starting calculating the distance

       $theta = $lon1 - $lon2;
       $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
       $dist = acos($dist);
       $dist = rad2deg($dist);
       $miles = $dist * 60 * 1.1515;
       $unit = $miles * 1.609344;

       $distance = substr($unit,0,4);
       $cinema[$i]['cinemaname'] = $row['cinemaname'];
       $cinema[$i]['distance'] = $distance;
       $i++;
    }
}

function sortByOrder($a, $b) {
   return $a['distance'] - $b['distance'];
}

usort($cinema, 'sortByOrder');
点赞