我想要以下JSON:
{"success": false,"errors": {"err1": "some error","err2": "another error"}}
我使用的代码:
$rs = array("success"=>true);
$rs['errors'][] = array("err1"=>"some error");
$rs['errors'][] = array("err2"=>"another error");
json_encode($rs);
生成以下内容:
{"success":false,"errors":[{"err1":"some error"},{"err2":"another error"}]}
errors
应该是一个关联数组。
$rs = array('success' => false, 'errors' => array());
$rs['errors']['err1'] = 'some error';
$rs['errors']['err2'] = 'another error';
echo json_encode($rs);
errors
在一个数字数组中包含一个对象,而不是多个对象。这应该有效:
$a = array(
"success" => false,
"errors" => array(
"err1" => "some error",
"err2" => "another error"
)
);
json_encode($a);
您试图创建的JSON字符串中没有任何数组。它有嵌套的对象。您需要创建一个对象来复制JSON字符串,如下所示:
$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';