构建包含JSON字符串数组的JSON字符串

时间:2014-03-13 10:55:02

标签: php json

在PHP中,我试图将一个JSON字符串放在一起,该字符串返回时包含了take的状态以及可能发生的任何错误:

public function create() {
    $data = Validate::sanitize($_POST['data']);
    parse_str($data);

    // Something

    $this->JSONResponse[] = $this->addCost($shipmentId, $cost);

    $this->JSONResponse[] = '{"code":"0", "type":"info", msg":"Shipment created successfully."}';
    return '{"response":['.json_encode($this->JSONResponse).']}';
}

public function addCost($shipmentId, $cost) {
    if ($cost > 0) {
        // Something
    } else {
        return '{"code":"1", "type":"info", msg":"Cost not added as it was 0 or left out."}';
    }
}

我尝试过的方法包括上例中的方法不起作用。我得到一个不是JSON的字符串或一个由包含原始JSON字符串的索引组成的JSON对象。

如何才能输出我想要的内容?

2 个答案:

答案 0 :(得分:1)

您是否有理由手动编写JSON字符串而不是构建PHP array并利用json_encode函数

如果没有,你应该使用

public function addCost($shipmentId, $cost) {
    if ($cost > 0) {
        // Something
    } else {
        return json_encode(array("code"=>1, "type"=>"info", "msg"=>"message"));
    }
}

正如卡米所说,这是一个错字:

'{"code":"0", "type":"info", msg":"Shipment created successfully."}';

缺少"

'{"code":"0", "type":"info", "msg":"Shipment created successfully."}';

答案 1 :(得分:1)

不要手动创建字符串 - 创建PHP对象或数组 - 然后使用json_encode从中创建字符串。像这样:

public function create() {
    $data = Validate::sanitize($_POST['data']);
    parse_str($data);

    // Something

    $this->JSONResponse[] = $this->addCost($shipmentId, $cost);

    $this->JSONResponse[] = json_encode(array("code" => 0,
                                              "type" => "info",
                                              "msg"  => "Shipment created successfully."));
    return json_encode(array("response" => $this->JSONResponse[]));
}

public function addCost($shipmentId, $cost) {
    if ($cost > 0) {
        // Something
    } else {
        return array("code" => 1,
                     "type" => "info"
                     "msg"  => "Cost not added as it was 0 or left out.");
    }
}