user10844414
user10844414

Reputation:

How do you build multidimensional JSON arrays in PHP?

I need to encode a PHP array to JSON that would look like this :

{
    "recipient": {
        "address1": "19749 Dearborn St",
        "city": "Chatsworth",
        "country_code": "US",
        "state_code": "CA",
        "zip": 91311
    },
    "items": [
        {
            "quantity": 1,
            "variant_id": 2
        },
        {
            "quantity": 5,
            "variant_id": 202
        }
    ]
}

So far this is what I have :

$recipientdata = array("address1" => "$recipientStreetAddress","city" => "$recipientCity","country_code" => "$recipientCountry","state_code" => "$recipientStateCode","zip" => "$recipientPostalCode");
$payload = json_encode( array("recipient"=> $recipientdata ) );

How can I build an array exactly like the one shown above? Where and how do I add the items?

Upvotes: 1

Views: 50

Answers (3)

$data = array(
    "recipient" => array(
        "address1" => $recipientStreetAddress,
        "city" => $recipientCity,
        "country_code" => $recipientCountry,
        "state_code" => $recipientStateCode,
        "zip" => $recipientPostalCode
    ),
    "items" => array(
        array(
            "quantity" => 1,
            "variant_id" => 2
        ),
        array(
            "quantity" => 5,
            "variant_id" => 202
        ),
    )
);
$payload = json_encode($data);

Upvotes: 1

Tomaž Puhar
Tomaž Puhar

Reputation: 66

Another way of doing it is using the php standard object, way better is to program the entities out with classes but here is a quick mock.

    $recipient = new stdClass();
$recipient->address1 = '19749 Dearborn St';
$recipient->city = 'Chatsworth';
$recipient->country_code = 'US';
$recipient->state_code = 'CA';
$recipient->zip = '91311';

$item1 = new stdClass();
$item1->quantity = 1;
$item1->variant_id = 2;

$item2 = new stdClass();
$item2->quantity = 5;
$item2->variant_id = 202;

var_dump(json_encode(
    array(
        'recipient' => $recipient,
        'items' => array(
            $item1,
            $item2
        )
    )
));

Upvotes: 1

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You should have an array like the following structure

You can verify the JSON format online Online JSON Validator

$arr = [
  'recipient' => [
    'address1' => '19749 Dearborn St',
    'city'     => 'Chatsworth',
    'country_code' => 'US',
    'state_code' => 'CA',
    'zip' => 91311
  ],
  'items' => [
    [
        'quantity'   => 1,
        'variant_id' => 2
    ],
    [
        'quantity'   => 5,
        'variant_id' => 202
    ]
  ]
];
$jsonString = json_encode($arr);

https://3v4l.org/O1Cit

Upvotes: 1

Related Questions