结果$ this-> Post->仅在CakePHP中查找数组

时间:2013-10-26 21:35:24

标签: php json api cakephp cakephp-2.0

对于我的网络服务,我想在我的控制器中按照脚本输出稍微清晰一点:

$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
        }
    ]
}

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

1 个答案:

答案 0 :(得分:1)

在控制器中:

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

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