Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法使用PHP数组格式化JSON响应_Php_Arrays_Json_Formatting - Fatal编程技术网

无法使用PHP数组格式化JSON响应

无法使用PHP数组格式化JSON响应,php,arrays,json,formatting,Php,Arrays,Json,Formatting,我想要以下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)

我想要以下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"}]}

错误
应为关联数组

$rs = array('success' => false, 'errors' => array());
$rs['errors']['err1'] = 'some error';
$rs['errors']['err2'] = 'another error';
echo json_encode($rs);

错误
应为关联数组

$rs = array('success' => false, 'errors' => array());
$rs['errors']['err1'] = 'some error';
$rs['errors']['err2'] = 'another error';
echo json_encode($rs);

错误
在数字数组中包含单个对象,而不是多个对象。这应该起作用:

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

错误
在数字数组中包含单个对象,而不是多个对象。这应该起作用:

$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';

您试图创建的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';

这是正确的,但我想指出的是,没有必要将
$rs['errors']
声明为关联数组(甚至作为
$rs
的一部分)。当
$rs['errors']['err1']='some error'时,如果数组不存在,PHP将自动将索引添加到数组中被执行。@Matt:我意识到这一点,我更愿意显式声明所有使用过的对象。它可以被移除,是的。我确信你知道这一点;我只是想向阅读你答案的其他人指出这一点。:-)这是正确的,但我想指出的是,没有必要将
$rs['errors']
声明为关联数组(甚至作为
$rs
的一部分)。当
$rs['errors']['err1']='some error'时,如果数组不存在,PHP将自动将索引添加到数组中被执行。@Matt:我意识到这一点,我更愿意显式声明所有使用过的对象。它可以被移除,是的。我确信你知道这一点;我只是想向阅读你答案的其他人指出这一点。:-)谢谢大家的回复。这是一个很棒的论坛,一个很棒的专业团队。谢谢大家的回复。这样一个伟大的论坛和一个伟大的专业团队。