簡體   English   中英

如何在PHP中構建多維JSON數組?

[英]How do you build multidimensional JSON arrays in PHP?

我需要將PHP數組編碼為JSON,如下所示:

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

到目前為止,這就是我所擁有的:

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

如何構建一個與上面顯示的陣列完全相同的陣列? 我在哪里以及如何添加項目?

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

您應該有一個類似於以下結構的數組

您可以在線驗證JSON格式在線JSON驗證器

$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

另一種方法是使用php標准對象,更好的方法是使用類對實體進行編程,但這里是一個快速模擬。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM