将一个变量添加到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);
答案 0 :(得分:0)
可能你没有正确检索$ bran和$ package变量..
$result2 = mysqli_query($datacon,
"SELECT * FROM spreadsheet
WHERE brand = '".$brand."'
AND package = '".$package."'
AND HIDE_FROM_SEARCH = '0'
GROUP BY ACCTNAME ".$pages->limit.");
答案 1 :(得分:0)
首先,创建条目数组,并将其存储在数组中,我们将调用$rows
。
您希望在此处使用PHP函数usort
来提供自定义排序回调。
假设您有一个如下所示的数组:
$rows = array(
array("latitude" => 5, "distance" => 10),
array("latitude" => 10, "distance" => 5),
array("latitude" => 56, "distance" => 48)
);
您希望对此$rows
数组进行重新排序,以便latitude == 10
的条目为第一个,latitude == 5
为第二个,latitude == 56
为第三个,具体取决于它们的距离
usort($rows, function ($a, $b) {
$a = $a['distance'];
$b = $b['distance'];
return $a == $b ? 0 : $a > $b ? 1 : -1;
});
输出
Array
(
[0] => Array
(
[latitude] => 10
[distance] => 5
)
[1] => Array
(
[latitude] => 5
[distance] => 10
)
[2] => Array
(
[latitude] => 56
[distance] => 48
)
)
See this demonstration at ideone.com
或者,您可以尝试查找SortedArray实现,该实现将使元素在插入到数组时保持排序,而不是仅在您在数组上调用usort()
时。不过,对于这个问题来说,这有点太先进了。
答案 2 :(得分:0)
在while
循环后尝试此操作:
uasort($locationSort, 'sortBydistance');
// or uasort($locationSort, array($this, "sortBydistance")); if you are using withing a class
print_r($locationSort);
function sortBydistance($a, $b) {
if ($a['distance'] == $b['distance']) {
return 0;
}
return ($a['distance'] < $b['distance']) ? -1 : 1;
}