我正在使用 CakePHP 将 JSONS 发送到我的 Android 应用程序。我目前在我的模型中有这个功能,它可以让我在某个地方的某个半径内获得最近的位置:
public function getNearest($lat = 54.980503, $lng = -1.614349, $radius = 25, $max = 30)
{
$query = "SELECT *,
( 3959 * acos( cos( radians('$lat') ) * cos(radians(`lat`))
* cos(radians(`long`) - radians('$lng') )
+ sin( radians('$lat') ) * sin( radians(`lat`) ) ) )
AS distance FROM locations HAVING distance < '$radius' ORDER BY distance LIMIT 0 , {$max}";
return $this->query($query);
}
这是我的控制器:
class LocationsController extends AppController
{
public $helpers = array('Html', 'Form');
public $components = array('RequestHandler');
public $viewClass = 'Json';
function index()
{
$locations = $this->Location->getNearest();
$this->set(compact('locations'));
$this->set('_serialize', array('locations'));
}
}
这是它以正常数组格式给我的输出:
array(2)
{
[0]=> array(2)
{
["locations"]=> array(9)
{
["id"]=> string(1) "1"
["name"]=> string(20) "Newcastle University"
["terrain"]=> string(1) "5"
["difficulty"]=> string(1) "2"
["ratings"]=> string(1) "4"
["uid"]=> string(1) "2"
["long"]=> string(8) "-1.61624"
["comid"]=> NULL
["lat"]=> string(7) "54.9787"
}
[0]=> array(1)
{
["distance"]=> string(19) "0.14548355269404845"
}
}
[1]=> array(2)
{
["locations"]=> array(9)
{
["id"]=> string(1) "2"
["name"]=> string(10) "Vale House"
["terrain"]=> string(1) "4"
["difficulty"]=> string(1) "3"
["ratings"]=> string(1) "4"
["uid"]=> string(1) "2"
["long"]=> string(8) "-1.58939"
["comid"]=> NULL
["lat"]=> string(7) "54.9849"
}
[0]=> array(1)
{
["distance"]=> string(18) "1.0352356381517442" }
}
}
如果我在 CakePHP 中打开 JSONView 类,我会得到:
{
"locations":[
{
"locations":{
"id":"1",
"name":"Newcastle University",
"terrain":"5",
"difficulty":"2",
"ratings":"4",
"uid":"2",
"long":"-1.61624",
"comid":null,
"lat":"54.9787"
},
"0":{
"distance":"0.14548355269404845"
}
},
{
"locations":{
"id":"2",
"name":"Vale House",
"terrain":"4",
"difficulty":"3",
"ratings":"4",
"uid":"2",
"long":"-1.58939",
"comid":null,
"lat":"54.9849"
},
"0":{
"distance":"1.0352356381517442"
}
}
]
}
如您所见,其中有很多不必要的字符串,例如,为什么有 3 个位置?为什么距离是分开的?
如果输出可以遵循以下原则,那就太好了:
{
"locations":
[{
"id":"1",
"name":"Newcastle University",
"terrain":"5",
"difficulty":"2",
"ratings":"4",
"uid":"2",
"long":"-1.61624",
"comid":null,
"lat":"54.9787"
"distance":"0.14548355269404845"
},
{
"id":"2",
"name":"Vale House",
"terrain":"4",
"difficulty":"3",
"ratings":"4",
"uid":"2",
"long":"-1.58939",
"comid":null,
"lat":"54.9849"
"distance":"1.0352356381517442"
}
]
}