我正在使用Codeigniter作为我的框架,我已经查看了文档,但我找不到解决方案。
现在我已经从数据库中选择了数据,我需要在检索到的每条记录的末尾显示距离。
Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus"}]}
这就是它需要的东西,请记住,距离不在数据库中,而是在运行中计算。
Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus", "distance": "1.2 Mi"}]}
有关如何将距离的任何想法附加到每个结果的末尾?
$dbStations->select('lat');
$dbStations->select('lng');
$dbStations->select('_id');
$stations = $dbStations->get('stDetails');
foreach ($stations->result() as $station) {
$lat2 = $station->lat;
$lng2 = $station->lng;
$stId = $station->_id;
$distance = $this->distance->gpsdistance($lat1, $lng1, $lat2, $lng2, "M");
if ($distance <= $rad) {
//at this point the code has determined that this id is within
//the preferred distance.
$stationArr[] = $stId;
}
}
$dbStations->select('country, _id, lat, lng, admin_level_1, locale');
$dbStations->where_in('_id', $stationArr);
$stations = $dbStations->get('stationDetails');
echo json_encode(array('stations' => $stations->result()));
}
答案 0 :(得分:1)
您可以尝试一次完成所有事情。根据可能知道您的表格,此查询应该为您提供半径$rad
内的工作站。
必须定义变量$lat1
和$lng1
。
$query= "select country, _id, lat, lng, admin_level_1, locale,
(acos(sin(radians($lat1)) * sin(radians(lat)) + cos(radians($lat1)) *
cos(radians(lat)) * cos(radians($lng1) - radians(lng))) * 6378)
as distance
from stationDetails
where (acos(sin(radians($lat1)) * sin(radians(lat)) +
cos(radians($lat1)) * cos(radians(lat)) * cos(radians($lng1) -
radians(lng))) * 6378)<=$rad
order by distance desc";
echo json_encode($this->db->query($query)->result_array());
注意:距离以米为单位。
答案 1 :(得分:1)
假设$dbStations->get('stDetails')
和$dbStations->get('stationDetails')
正在查询同一个表,您可以这样做:
$dbStations->select('country, _id, lat, lng, admin_level_1, locale');
$stations = $dbStations->get('stDetails');
$output = array();
foreach ($stations->result() as $station) {
$lat2 = $station->lat;
$lng2 = $station->lng;
$distance = $this->distance->gpsdistance($lat1, $lng1, $lat2, $lng2, "M");
if ($distance <= $rad) {
$station->distance = $distance;
$output[] = $station;
}
}
echo json_encode($output);
我没有对此进行测试,它可能无法准确地给出您想要的内容,因此您可能需要对其进行一些调整。重要的是我是如何做到的。抓取开头的所有数据,然后验证每一行。如果行有效(在一定距离内),请将距离添加到阵列并保存以便输出。当没有剩余行时,输出有效站。