【问题标题】:Unable to format JSON response with PHP Arrays无法使用 PHP 数组格式化 JSON 响应
【发布时间】:2026-01-04 14:10:02
【问题描述】:

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

【问题讨论】:

    标签: php arrays json formatting


    【解决方案1】:

    errors 应该是一个关联数组。

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

    【讨论】:

    • 这是正确的,但我想指出,没有必要将$rs['errors'] 声明为关联数组(甚至根本不需要作为$rs 的一部分)。执行$rs['errors']['err1'] = 'some error';时,如果数组不存在,PHP会自动添加索引。
    • @Matt:我意识到这一点并且更喜欢明确声明所有使用的对象。可以删除,是的。
    • 我确信你知道这一点;我只是想向其他阅读您的答案的人指出这一点。 :-)
    【解决方案2】:

    errors 包含单个对象,而不是数值数组中的多个对象。这应该有效:

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

    【讨论】:

    • 感谢大家的回复。如此出色的论坛和众多专业人士。
    【解决方案3】:

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

    【讨论】: