how to create JSON array [] for REST response?

Question

I am trying to create a REST response for a self-developed API in WordPress. The current code is

    $response = array();

    $response[] = array(
        'version' => '1.0',
        'user' => array(
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->user_email,
            'id' => $user->ID,
        ),
    );

return rest_ensure_response( $response );

Which returns (i am using a user object)

[
{
"version": "1.0",
"user": {
    "first_name": "Test",
    "last_name": "User",
    "email": "test@test.xyz",
    "id": 19
}
}
]

However i need it in this form

[
  {
"version": "1.0",
"user": [
    {
        "first_name": "Test",
        "last_name": "User",
        "email": "stather@auktionen-in-heidelberg.de",
        "id": 19,
    }
    ]
  }
]

So the challenge here is how to get the [] around the "user"?

This is more likely a general questions as im unable to add the "[" and "]" manually to the response array

Best, Thomas

0
Thomy1985 2 months 0 Answers 13 views 0

Leave an answer