如何在PHP中构建多维JSON数组?

时间:2019-06-25 18:10:17

标签: php arrays

我需要将一个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 ) );

如何构建与上面显示的数组完全相同的数组?我在哪里以及如何添加项目?

3 个答案:

答案 0 :(得分:2)

char*

答案 1 :(得分:1)

您应该拥有一个类似于以下结构的数组

您可以在线Online JSON Validator验证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

答案 2 :(得分:1)

另一种实现方法是使用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
        )
    )
));