在 CakePHP 2.4 中,为了自定义控制器的 JSON 输出的内容和结构,通过我的数据foreach
正确的语法是什么?
目前有以下方法,它创建一个 .json,直接镜像我所有帖子的 Cake 内部数组:
public function points() {
$this->autoRender = false; // We don't render a view in this example
$this->Post->recursive = -1; //Don't return stuff we don't need
return json_encode($this->Post->find('all'));
}
这将创建如下所示的JSON,每个帖子的数据都是其自己的Post对象的子对象(使用回车符进行美化,以便您可以阅读它):
[{"Post":{"id":"1",
"user_id":"1",
"organism_id":"0",
"title":"Title Text",
"lat":"44.54401744186992",
"lng":"-68.26070404052734",
"body":"Body Text",
"created":"2014-01-19 07:13:29",
"modified":"2014-01-19 07:13:29"}
},
{"Post":{"id":"2",
"user_id":"1",
"organism_id":"0",
"title":"Title Text",
"lat":"44.54401744186992",
"lng":"-68.26070404052734",
"body":"Body Text",
"created":"2014-01-19 07:13:29",
"modified":"2014-01-19 07:13:29"}
}]
这是一个问题,因为 (A) 出于性能原因,我可能不想将每个帖子的所有数据转储到 JSON 中,并且 (B) 为了输出到 Google 地图,我需要将每个帖子的数据输出为一个 Posts 对象的子对象,如下所示:
{"Posts":[
{"id":"1",
"user_id":"1",
"organism_id":"0",
"title":"Title Text",
"lat":"44.54401744186992",
"lng":"-68.26070404052734",
"body":"Body Text",
"created":"2014-01-19 07:13:29",
"modified":"2014-01-19 07:13:29"
},
{"id":"2",
"user_id":"1",
"organism_id":"0",
"title":"Title Text",
"lat":"44.54401744186992",
"lng":"-68.26070404052734",
"body":"Body Text",
"created":"2014-01-19 07:13:29",
"modified":"2014-01-19 07:13:29"}]}
我知道我需要以某种方式foreach
数据并构建一个数组。这是如何工作的? foreach ($posts as $post):
在控制器内部不起作用。
试试这个...
$data = array();
foreach ($posts as $post) {
$data[] = $post['Posts'];
}
$postdata['Posts'] = $data;
echo json_encode($postdata);
我找到了解决方案!
在控制器中:
public function points() {
$this->request->onlyAllow('ajax'); //Don't respond to non-AJAX requests
$this->Post->recursive = -1; //don't return info from other controllers
$this->set('posts', $this->Post->find('all'));
}
在/view/posts/json/points.ctp 中:
foreach ($posts as $post) {
$markers[] = array(
'id' => $post['Post']['id'],
'lat' => $post['Post']['lat'],
'lng' => $post['Post']['lng']
); //make an array of the contents of each post I want to include
}
$data = array(
'Posts' => $markers); //Make everything the child of a 'Posts' object
echo json_encode($data); //Turn it into JSON!
您还可以使用Hash
实用程序:
$posts = $this->Post->find('all');
$posts = array('Posts' => Hash::extract($posts, '{n}.Post'));
$this->set('posts', posts);