Ondrej Rafaj
Ondrej Rafaj

Reputation: 4417

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

For my web service, I would like to have slightly cleaner output, following script in my controller:

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

when run through json_encode looks like this:

{
    "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
            }
        }
    ]
}

But the version I would like looks like this:

{
    "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
        }
    ]
}

I know in my template I can go through the array recursively but I hoped there could be a more elegant solution for this.

Upvotes: 0

Views: 75

Answers (1)

Aleksandr  Cerleniuk
Aleksandr Cerleniuk

Reputation: 96

In controller:

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

Maybe this will be more elegant for you )

Upvotes: 1

Related Questions