Matthijs
Matthijs

Reputation: 57

Add array to array with PHP in JSON

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

Upvotes: 1

Views: 45

Answers (1)

lukas.j
lukas.j

Reputation: 7163

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

Upvotes: 1

Related Questions