json_encode

时间:2018-04-17 19:26:36

标签: php arrays json multidimensional-array

我需要传递一个json一个元素如何一个elemnts数组

纠正json:

{
    "issued": true,
    "customer": 451071,
    "invoice_lines": [{
        "quantity": 1,
        "concept": "Renovar Dominio - xxx.org - 1 A\u00f1o(s) (22\/03\/2018 - 21\/03\/2019) + Protecci\u00f3n de ID",
        "amount": 13.15,
        "discount": 0,
        "tax": 21,
        "retention": 0
    }, {
        "quantity": 1,
        "concept": "Renovar Dominio - xxx.net - 1 A\u00f1o(s) (22\/03\/2018 - 21\/03\/2019) + Protecci\u00f3n de ID",
        "amount": 12.73,
        "discount": 0,
        "tax": 21,
        "retention": 0
    }],
    "charges": [{
        "date": "2018-03-05",
        "amount": 74.69,
        "method": "paypal",
        "destination_account": 39720,
        "charged": true
    }],
    "date": "2018-03-05",
    "number": 4
}

好吧,在我的代码之前json_encode尝试了几种方法,但所有时间都得到不正确的json

{
    "issued": true,
    "customer": 451071,
    "invoice_lines": [
        [{
            "quantity": 1,
            "concept": "Renovar Dominio - xxx.org - 1 A\u00f1o(s) (22\/03\/2018 - 21\/03\/2019) + Protecci\u00f3n de ID",
            "amount": 13.15,
            "discount": 0,
            "tax": 21,
            "retention": 0
        }, {
            "quantity": 1,
            "concept": "Renovar Dominio - xxxx.net - 1 A\u00f1o(s) (22\/03\/2018 - 21\/03\/2019) + Protecci\u00f3n de ID",
            "amount": 12.73,
            "discount": 0,
            "tax": 21,
            "retention": 0
        }]
    ],
    "charges": [{
        "date": "2018-03-05",
        "amount": 74.69,
        "method": "paypal",
        "destination_account": 39720,
        "charged": true
    }],
    "date": "2018-03-05",
    "number": 4
}

在我的PHP代码中尝试其他人但遇到同样的问题:

$invoiceLines = array();

foreach ($whmcsLines as $whmcsLine) {
    $lines = [
        'quantity' => 1,
        'concept' => str_replace("\n","",$whmcsLine->description),
        'amount' => (double)$whmcsLine->amount,
        'discount' => 0,
        'tax' => $whmcsLine->taxed ? 21 : 0,
        'retention' => 0
    ];

    array_push($invoiceLines, $line);

}

编辑:

在处理完所有ellemnts之后:

$newInvoice = array(
            'issued' => true,
            'customer' => $this->customerId,
            'invoice_lines'=> array($invoiceLines),
            'charges' => array($paymentLines),
            'date' => $this->lastDate,
            'number' => $this->nextInvoice
        );

$this->someAction(json_encode($newInvoice)));

1 个答案:

答案 0 :(得分:2)

'invoice_lines'=> array($invoiceLines),
'charges' => array($paymentLines),

这是不正确的 - 它将$invoiceLines$paymentLines(已经是数组)包装在一个额外的数组中。

你想要的只是:

'invoice_lines' => $invoiceLines,
'charges' => $paymentLines,