0

对于我的 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
        }
    ]
}

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

4

1 回答 1

1

在控制器中:

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

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

于 2013-10-26T21:59:03.370 回答