【发布时间】:2014-02-28 18:47:58
【问题描述】:
在 mysql 查询的末尾添加一个变量。 现在我需要能够按关联值排序。有人可以帮忙吗?我尝试了几种不同的排序方法。
$result2 = mysqli_query($datacon,
"SELECT * FROM spreadsheet
WHERE brand = '$brand'
AND package = '$package'
AND HIDE_FROM_SEARCH = '0'
GROUP BY ACCTNAME $pages->limit");
echo mysqli_error($datacon);
while($row = mysqli_fetch_array($result2)) {
$lat_B=$row['LATITUDE'];
$long_B=$row['LONGITUDE'];
$lat_A = round($lat_A,2);
$long_A = round($long_A,2);
$lat_B = round($lat_B,2);
$long_B = round($long_B,2);
$distance = new calcDist($lat_A, $long_A, $lat_B, $long_B);
$distance = $distance->calcDist($lat_A, $long_A, $lat_B, $long_B);
$distance = round($distance,2);
$locationSort=array($row);
$locationSort['distance']=$distance;
FOR EACH SOMETHING?
}
我已经修改了我之前的帖子以反映我对答案的使用。
$result2 = mysqli_query($datacon,"SELECT * FROM spreadsheet WHERE brand = '$brand'
AND package = '$package' and HIDE_FROM_SEARCH = '0' GROUP BY ACCTNAME $pages->limit");
echo(mysqli_error($datacon));
class sortBydistance
{
function sortBydistance($a, $b) {
if ($a['distance'] == $b['distance']) {
return 0;
}
return ($a['distance'] < $b['distance']) ? -1 : 1;
}
}
while($row = mysqli_fetch_array($result2))
{
$lat_B=$row['LATITUDE'];
$long_B=$row['LONGITUDE'];
$lat_A = round($lat_A,2);
$long_A = round($long_A,2);
$lat_B = round($lat_B,2);
$long_B = round($long_B,2);
$distance = new calcDist($lat_A, $long_A, $lat_B, $long_B);
$distance = $distance->calcDist($lat_A, $long_A, $lat_B, $long_B);
$distance = round($distance,2);
}
$locationSort=array($row);
$locationSort['distance']=$distance;
uasort($locationSort, array($this, "sortBydistance"));
print_r($locationSort);
【问题讨论】:
-
不清楚您希望在这里完成什么。你能扩展你的问题吗?
-
基本上我从数据库中获取位置,然后在 while 循环中计算距离。我现在需要做的是将变量“距离”添加到数组中。然后按该数组内的距离排序。我已经能够将距离添加到数组中,但我无法让数组按距离排序。
-
您可以为函数
usort提供一个排序回调,它允许您根据距离值进行排序。 -
我试过了,但我不明白如何具体按距离变量排序。
-
警告:asort() 期望参数 2 很长,当我尝试这个时给出字符串:asort($locationSort, 'distance'); print_r($locationSort);