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 に答える