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);
3
  • Each time you are calling arr[], you are creating a new element. You should add them all to an array and then create 1 new element for it as @NigelRen suggested below. Commented Nov 1, 2019 at 7:39
  • No upvotes on this page, so can't add to the dupe list: stackoverflow.com/q/51354958/2943403 Commented Nov 1, 2019 at 8:22
  • And stackoverflow.com/q/16308252/2943403 Commented Nov 1, 2019 at 9:03

1 Answer 1

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];

} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.