【问题标题】:php build array/json object structure [duplicate]php构建数组/ json对象结构[重复]
【发布时间】:2020-02-27 13:01:13
【问题描述】:

尝试基于我尝试连接的 API 来实现这种 jsondata 结构:

{
    "VoucherDate": "2019-10-27",
    "VoucherText": "string",
    "VoucherType": 2,
    "Rows": [{
            "AccountNumber": 0,
            "DebitAmount": 0,
            "CreditAmount": 0,
            "TransactionText": "string"
        },
        {
            "AccountNumber": 0,
            "DebitAmount": 0,
            "CreditAmount": 0,
            "TransactionText": "string"
        }
    ]
}

到目前为止,我在下面试验过的代码生成了这个结构。 Rows 数组没有得到和上面一样的结构,我哪里做错了?

{
    "VoucherDate": "2019-10-31",
    "VoucherText": "string",
    "VoucherType": 2,
    "Rows": [{
        "TransactionText": "test"
    }, {
        "AccountNumber": 1000
    }, {
        "DebitAmount": 1
    }, {
        "CreditAMount": 2
    }, {
        "TransactionText": "test"
    }, {
        "AccountNumber": 1000
    }, {
        "DebitAmount": 1
    }, {
        "CreditAMount": 2
    }]
}

php代码:

$postdata = array();
$postdata["VoucherDate"] = "2019-10-31";
$postdata["VoucherText"] = "string";
$postdata["VoucherType"] = 2; 
$postdata["Rows"] = array();

for ($x = 1; $x <= 10; $x++) { 
    $postdata["Rows"][]["TransactionText"] = "string";
    $postdata["Rows"][]["AccountNumber"] = 0;
    $postdata["Rows"][]["DebitAmount"] = 0;
    $postdata["Rows"][]["CreditAMount"] = ;

}   

echo json_encode($postdata);

【问题讨论】:

标签: php arrays json object


【解决方案1】:

您需要先将所有元素添加到一个数组中,然后再将它们添加到整体数据中,例如......

for ($x = 1; $x <= 10; $x++) { 
    $postdata["Rows"][] = ["TransactionText" => "string", 
                           "AccountNumber" => 0,
                           "DebitAmount" => 0,
                           "CreditAMount" = 2];

} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-12
    • 2019-08-20
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2018-03-02
    • 2019-09-25
    • 1970-01-01
    相关资源
    最近更新 更多