php - 在 Curl 函数中运行 foreach 循环
问题描述
我需要在 curl 命令中运行一个 foreach 循环,但不能完全正确地获取语法。我已经很好地解析了其他变量,但它只是格式化我的数组以适应。
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"order\": {
\"channel_id\": $channel_id,
\"customer_id\": $customer_id,
\"deliver_to_id\": $deliver_to_id,
\"delivery_method_id\": $delivery_method_id,
\"line_items_attributes\": [
{
\"sellable_id\": 39236017,
\"price_per_unit\": \"1.000\",
\"quantity\": \"10\"
}
],
}
}");
这是我的数组:
Array
(
[0] => Array
(
[0] => Array
(
[id] => 39235995
[quantity] => 1
[price] => 2.81
)
[1] => Array
(
[id] => 39235995
[quantity] => 1
[price] => 2.81
)
[2] => Array
(
[id] => 39236029
[quantity] => 0
[price] => 2.952
)
[3] => Array
(
[id] => 39236015
[quantity] => 0
[price] => 3.333
)
)
)
我需要将我的数组专门推入这个部分:
\"sellable_id\": 39236017,
\"price_per_unit\": \"1.000\",
\"quantity\": \"10\"
这是我的尝试,但这会导致各种问题,我哪里出错了?
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"order\": {
\"channel_id\": $channel_id,
\"customer_id\": $customer_id,
\"deliver_to_id\": $deliver_to_id,
\"delivery_method_id\": $delivery_method_id,
\"line_items_attributes\": [
{
foreach($parcels[0] as $item){
\"sellable_id\": $item['id'],
\"price_per_unit\": $item['price'],
\"quantity\": $item['quantity'],
}
}
],
}
}");
稍微补充一下,如果数组是这个并且我没有以它为目标foreach($parcels[0] as $item) {
但它是foreach($parcels as $item) {
相反的呢?
Array
(
[0] => Array
(
[0] => Array
(
[id] => 39235995
[quantity] => 1
[price] => 2.46
)
[1] => Array
(
[id] => 39236017
[quantity] => 1
[price] => 2.75
)
)
[1] => Array
(
[0] => Array
(
[id] => 39236029
[quantity] => 1
[price] => 2.58
)
)
)
解决方案
您不能只是将 PHP 代码放在字符串中并期望它被执行。您必须转换您的数组,然后传递给 cUrl:
$order = [
"order" => [
"channel_id" => $channel_id,
"customer_id" => $customer_id,
"deliver_to_id" => $deliver_to_id,
"delivery_method_id" => $delivery_method_id,
"line_items_attributes" => [
[
"sellable_id": 39236017,
"price_per_unit": "1.000",
"quantity": "10"
]
],
]
];
foreach($parcels[0] as $item) {
$order['order']['line_items_attributes'][] = [
"sellable_id" => $item['id'],
"price_per_unit" => $item['price'],
"quantity" => $item['quantity'],
];
}
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($order));
推荐阅读
- python - 创建一个从 2 到 20 的偶数数组。然后使用 for 循环和附加函数,将可被 7 整除的数字从 30 到 50 插入到 pytho 中的该数组中
- excel - VBA Find and Format Specific Text In Worksheet (Not entire Cell)
- laravel - Explicitly providing "user_id" to Revisionable
- powershell - 通过Jenkins运行Powershell脚本时如何修复“脚本返回退出代码1”?
- mysql - MySQL:从按距离排序的表中返回前三个条目:将纬度和对数作为参数
- java - Java 代码中的 JMeter 测试 - 生成与 GUI 报告匹配的控制台/文件报告
- r - 警告:超出速率限制 - 88(超出速率限制)与 `rtweet`
- java - 为什么 intellij 在新模块中生成主模块和测试模块
- c - 没有 dup2 系统调用的操作系统上最简单的解决方法是什么?
- solr - SOLR - 同时添加文档的多个请求部分失败