$this->Post->find 的结果仅在 CakePHP 中作为数组


Results for $this->Post->find as array only in CakePHP

对于我的 Web 服务,我希望输出稍微干净一点,在我的控制器中遵循以下脚本:

$this->set('data', $this->Post->find('all'));

运行时json_encode如下所示:

{
    "timestamp": 1382822815,
    "data": [
        {
            "Post": {
                "id": "1",
                "title": "The title",
                "body": "This is the post body.",
                "created": "2013-10-26 15:19:31",
                "modified": null
            }
        },
        {
            "Post": {
                "id": "2",
                "title": "The title",
                "body": "This is the post body.",
                "created": "2013-10-26 15:19:31",
                "modified": null
            }
        }
    ]
}

但是我想要的版本看起来像这样:

{
    "timestamp": 1382822815,
    "data": [
        {
            "id": "1",
            "title": "The title",
            "body": "This is the post body.",
            "created": "2013-10-26 15:19:31",
            "modified": null
        },
        {
            "id": "2",
            "title": "The title",
            "body": "This is the post body.",
            "created": "2013-10-26 15:19:31",
            "modified": null
        }
    ]
}

我知道在我的模板中我可以递归浏览数组,但我希望有一个更优雅的解决方案。

在控制器中:

$posts = $this->Post->find('all');
$data = array_map('reset', $posts);
$this->set(compact('data'));

也许这对你来说会更优雅)