0

Trying to achieve this structure of jsondata based on an API I am trying to connect to:

{
    "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"
        }
    ]
}

The code I have experimented with so far, below, generates this structure. The Rows array doesn't get the same structure as above, where do I do wrong?

{
    "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 code:

$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);
Kevin Lindmark
  • 1,155
  • 3
  • 13
  • 26

1 Answers1

3

You need to add all of the elements into one array before adding them to your overall data, something like....

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

} 
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55