0

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": "[email protected]",
    "id": 19
}
}
]

However i need it in this form

[
  {
"version": "1.0",
"user": [
    {
        "first_name": "Test",
        "last_name": "User",
        "email": "[email protected]",
        "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

1 Answer 1

1

Just use another array() inside user array()

$response = array();

$response[] = array(
    'version' => '1.0',
    'user' => array(
        array(
            'first_name' => 'Razon',
            'last_name' => 'komar pal',
            'email' => '[email protected]',
            'id' => 10,
        )
    ),
);

return rest_ensure_response($response);

It will output like:

[
    {
        "version": "1.0",
        "user": [
            {
                "first_name": "Razon",
                "last_name": "komar pal",
                "email": "[email protected]",
                "id": 10
            }
        ]
    }
]

Hope this will work for you :)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.