在CakePHP中自定义JSON输出

时间:2014-02-17 23:32:52

标签: php json cakephp cakephp-2.0

在CakePHP 2.4中,为了从我的控制器自定义JSON输出的内容和结构,通过我的数据foreach的正确语法是什么?

我目前有以下方法,它创建一个直接镜像我所有帖子的Cake内部数组的.json:

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 Maps,我需要将每个帖子的数据输出为一个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):在控制器内部无效。

3 个答案:

答案 0 :(得分:1)

试试这个......

$data = array();
foreach ($posts as $post) {
      $data[] = $post['Posts'];
}

$postdata['Posts'] = $data;

 echo json_encode($postdata); 

答案 1 :(得分:0)

我找到了解决方案!

在控制器中:

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!

答案 2 :(得分:0)

您还可以使用Hash实用程序:

    $posts = $this->Post->find('all');
    $posts = array('Posts' => Hash::extract($posts, '{n}.Post'));
    $this->set('posts', posts);