0

I want the following JSON:

{"success": false,"errors": {"err1": "some error","err2": "another error"}}

The code I am using:

$rs = array("success"=>true);
$rs['errors'][] = array("err1"=>"some error");
$rs['errors'][] = array("err2"=>"another error");
json_encode($rs);

produces the following:

{"success":false,"errors":[{"err1":"some error"},{"err2":"another error"}]}

3 Answers 3

4

errors should be an associative array.

$rs = array('success' => false, 'errors' => array());
$rs['errors']['err1'] = 'some error';
$rs['errors']['err2'] = 'another error';
echo json_encode($rs);
Sign up to request clarification or add additional context in comments.

3 Comments

This is correct, but I wanted to point out that it's not necessary to declare $rs['errors'] as an associative array (or even as part of $rs at all). PHP will automatically add the index to the array if it doesn't exist when $rs['errors']['err1'] = 'some error'; is executed.
@Matt: I realize that and prefer to declare all used objects explicitly. It can be removed, yes.
I was certain you knew this; I just wanted to point it out to anyone else reading your answer. :-)
0

errors contains a single object, not multiple objects in a numeric array. This should work:

$a = array(
  "success" => false,
  "errors" => array(
    "err1" => "some error",
    "err2" => "another error"
  )
);
json_encode($a);

1 Comment

Thanks all for your responses. Such a great forum and a great group of professionals.
0

The JSON string you are trying to create does not have any arrays in it. It has nested objects. You would need to create an object in order to replicate that JSON string like this:

$root_obj = new StdClass();
$root_obj->success = false;
$root_obj->errors = new StdClass();
$root_obj->errors->err1 = 'some error';
$root_obj->errors->err2 = 'another error';

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.