PHP JSON编码转换为带有方括号的cUrl多维数组



我正在学习教程

这应该是我的输出(期望的结果(:

{
"intent": "CAPTURE",
"purchase_units": [
{
"reference_id": "ABC123",
"amount": {
"currency_code": "USD",
"value": "100.00"
}
}
],
"application_context": {
"return_url": "https://example.com/return",
"cancel_url": "https://example.com/cancel"
}
}

然而,在一个PHP数组和使用json_encode转换后,我得到了这个结果

{
"intent": "CAPTURE",
"purchase_units": {
"reference_id": "ABC123",
"amount": {
"currency_code": "USD",
"value": 100
}
},
"application_context": {
"return_url": "https://example.com/return",
"cancel_url": "https://example.com/exit"
}
}

最明显的区别可以在这里找到——所需的结果是"purchase_units": [{}],,而我的输出是返回"purchase_units": {和"}",没有方括号。

这是我的PHP代码:

$seller = array(
'intent' => 'CAPTURE',
'purchase_units' => array(
'reference_id' => 'ABC123',
'amount' => array(
'currency_code' => 'USD',
'value' => 100.00
),
),
'application_context' => array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/exit',
),
);

purchase_units需要是一个数组数组。也就是说,一个外部索引数组变为JSON数组,其中包含变为JSON对象的关联数组。

$seller = [
'intent' => 'CAPTURE',
'purchase_units' => [[ // 👈 note the nested array
'reference_id' => 'ABC123',
'amount' => [
'currency_code' => 'USD',
'value' => 100.00
],
]], // 👈 and close it here
'application_context' => [
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/exit',
],
];
$json = json_encode($seller, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

您并不真正需要JSON_PRETTY_PRINT,但您可能希望保留JSON_UNESCAPED_SLASHES选项。

演示~https://3v4l.org/ZdqcR

最新更新