3
    $user = $this->User->find( 'all' );
    $this->set( 'users', $user );

I have this code in my controller.

In my view I have this.

echo json_encode( compact( 'users' ) );

It outputs json like this

    {
    "users": [{
        "User": {
            "user_id": "2",
            "email": "[email protected]",
            "name": "Blah"
        }]
    }
}

Is there anyway to format this to remove the entire array wrapped in "users", and also remove every object being a member of "User".

This makes it harder to use on the front end. I'd like it to look like this.

[{
    "user_id": "2",
    "email": "[email protected]",
    "name": "Blah"
}]

Thanks for any help.

2 Answers 2

7

I don't fully understand what you mean by "remove the entire array wrapped in "users"" and "remove every object being a member of "User"", but according to your desired output format example, you'll need to extract and pass the exact data that you want to be encoded to json_encode, instead of passing everything using compact.

Extracting could be done with the Set or the Hash class (depending on your Cake version)

Assuming your model returns the data in the default CakePHP format, this for example:

json_encode(Set::extract('/User/.', $users));

should give you a structure like this:

[{
    "user_id": "2",
    "email": "[email protected]",
    "name": "Blah"
}]

and with multiple users it should look like this

[{
    "user_id": "1",
    "email": "[email protected]",
    "name": "Bar"
},
{
    "user_id": "2",
    "email": "[email protected]",
    "name": "Blah"
}]
Sign up to request clarification or add additional context in comments.

Comments

0

Use like this:

$users= (Set::extract('/User/.', $users));
pr($users);

It will remove Model from result Array and then json_encode or whatever further usage.

More library functions Set class Here and Hash class Here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.