我想用API通过post方法发送请求,当发送值时,有时我需要发送两个值而不是一个,为此我需要循环它。解决这个问题的方法是,在发送请求之前,我将其保存到循环中的数组中,并尝试通过创建json_encode来完成这个过程。
我的解释可能不完全解释,所以我将通过代码解释。
我想抛出的请求通常如下所示:
CURLOPT_POSTFIELDS =>'
[
{
"items":
[
{
"name":"string",
"sku":"string",
}
],
}
]'但有时,项目值需要有两个而不是一个。例如:
CURLOPT_POSTFIELDS =>'
[
{
"items":
[
{
"name":"string",
"sku":"string",
},
{
"name":"string",
"sku":"string",
}
],
}
]'因此,在提出此请求之前,我将将这些值保存到foreach循环中的数组中。
$data =array();
foreach ($request->orderItems as $orderItemId) {
$order_item = OrderItem::where('orderItemId',$orderItemId)->first();
$data[] = array(
"sku"=> $order_item->sku,
"name"=> $order_item->name,
)
}如果我要发送多个值,我的最后代码如下所示。
CURLOPT_POSTFIELDS =>'
[
{
"items": '.json_encode($data).',
}
]'这里是问题开始的地方,,当我试图发送这个请求时,我得到了这个错误:
数组到字符串转换
我到底该怎么做?我在哪里失踪了?
发布于 2022-07-27 09:34:16
您可能丢失了Content-Type调用的cURL头。
CURLOPT_HTTPHEADER => [
'Content-Type' => 'application/json',
],发布于 2022-07-27 13:05:19
尝试像这样对CURLOPT_POSTFIELDS中的所有内容进行编码
$array = [
array(
"name" => "string",
"sku" => "string",
),
array(
"name" => "string",
"sku" => "string",
)
];
$final = json_encode([["items" => $array]]);
//now use this variable directly in CURLOPT_POSTFIELDS
CURLOPT_POSTFIELDS => $final希望它能帮上忙..。
https://stackoverflow.com/questions/73135424
复制相似问题