Мне нужно закодировать массив 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);
Другой способ сделать это - использовать стандартный объект 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
)
)
));
не надо гадать. Просто используйте
var_export(json_decode($your_json_string, true));, чтобы получить структуру исходного массива