1

I'm using the PHP code below to generate a JSON call.

$Services = array();

$ServiceList[] = array(
  'Name' => 'ideal',
  'Action' => 'Pay'
);
$postArray["Services"]["ServiceList"] = $ServiceList;

$Parameters[] = array(
    'Name' => 'issuer',
    'Value' => 'ASNBNL21'
);
$postArray["Services"]["ServiceList"]["Parameters"] = $Parameters;

$postjson = json_encode($postArray, JSON_PRETTY_PRINT);

But when I generate the array "Servicelist" it gives me the wrong JSON code. It shows "0": { instead of the array braces.

"Services": {
        "ServiceList": {
            "0": {
                "Action": "Pay",
                "Name": "ideal"
            },
            "Parameters": [
                {
                    "Name": "issuer",
                    "Value": "ASNBNL21"
                }
            ]
        }
    }

The right JSON code should look like this:

"Services": {
    "ServiceList": [
      {
        "Name": "ideal",
        "Action": "Pay",
        "Parameters": [
          {
            "Name": "issuer",
            "Value": "ABNANL2A"
          }
        ]
      }
    ]
  }
2
  • Try changing $ServiceList[] to $ServiceList Commented Jan 1, 2022 at 17:44
  • Why create any single-use variables at all? 3v4l.org/QBdUl @Matt Commented Jan 1, 2022 at 19:21

1 Answer 1

1

Instead of starting on the top level, start with the innermost level:

$parameters = [ 'Name' => 'issuer', 'Value' => 'ASNBNL21' ];
$serviceList = [ 'Name' => 'ideal', 'Action' => 'Pay', 'Parameters' => [ $parameters ] ];
$services = [ 'ServiceList' => [ $serviceList ] ];
$postArray = [ 'Services' => $services ];

$postjson = json_encode($postArray, JSON_PRETTY_PRINT);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.