我想要以下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"}]}
答案 0 :(得分:4)
errors
应该是一个关联数组。
$rs = array('success' => false, 'errors' => array());
$rs['errors']['err1'] = 'some error';
$rs['errors']['err2'] = 'another error';
echo json_encode($rs);
答案 1 :(得分:0)
errors
包含单个对象,而不是数字数组中的多个对象。这应该有效:
$a = array(
"success" => false,
"errors" => array(
"err1" => "some error",
"err2" => "another error"
)
);
json_encode($a);
答案 2 :(得分:0)
您尝试创建的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';