这是CURL请求的发布字段。我需要向此CURLOPT_POSTFIELDS添加多个县ID:-
CURLOPT_POSTFIELDS => '{
"fields": [
{
"field_type": "countries",
"field_value":[
{
"country_id": '.$id.' ,
"match_type": "exact"
}
]
}
]
}'
我有一个国家/地区ID数组,需要为所有人创建此块:-
{
"country_id": '.$id.' ,
"match_type": "exact"
}
因此,如果我有5个国家/地区的ID,则应为
CURLOPT_POSTFIELDS => '{
"fields": [
{
"field_type": "countries",
"field_value":[
{
"country_id": '.$id[0].' ,
"match_type": "exact"
},
{
"country_id": '.$id[1].' ,
"match_type": "exact"
},
{
"country_id": '.$id[2].' ,
"match_type": "exact"
},
{
"country_id": '.$id[3].' ,
"match_type": "exact"
},
{
"country_id": '.$id[4].' ,
"match_type": "exact"
}
]
}
]
}'
国家/地区的数量可能每次都不同。因此,我需要在其中使用for循环来动态地进行操作。 在此先感谢
答案 0 :(得分:3)
极力建议在循环中手动制作json字符串。您应该先构建一个有效的数组,然后在完成后将其转换为json。
要构建所需的结果数组,只需将新数据推入适当的子数组即可。
代码:(Demo)
$country_ids = range(1,5);
$result['fields'][0]['field_type'] = "countries";
foreach ($country_ids as $id) {
$result['fields'][0]['field_value'][] = ["country_id" => $id, "match_type" => "exact"];
}
var_export($result);
echo "\n---\n";
echo json_encode($result, JSON_PRETTY_PRINT); // this resembles your posted data
输出(作为数组和json):
array (
'fields' =>
array (
0 =>
array (
'field_type' => 'countries',
'field_value' =>
array (
0 =>
array (
'country_id' => 1,
'match_type' => 'exact',
),
1 =>
array (
'country_id' => 2,
'match_type' => 'exact',
),
2 =>
array (
'country_id' => 3,
'match_type' => 'exact',
),
3 =>
array (
'country_id' => 4,
'match_type' => 'exact',
),
4 =>
array (
'country_id' => 5,
'match_type' => 'exact',
),
),
),
),
)
---
{
"fields": [
{
"field_type": "countries",
"field_value": [
{
"country_id": 1,
"match_type": "exact"
},
{
"country_id": 2,
"match_type": "exact"
},
{
"country_id": 3,
"match_type": "exact"
},
{
"country_id": 4,
"match_type": "exact"
},
{
"country_id": 5,
"match_type": "exact"
}
]
}
]
}
答案 1 :(得分:1)
您可以执行以下操作。
$id = array(1,2,3,4,5,6); // Your IDS
$numberOfIds = count($id); //Total number of ids (no comma after last entry)
$finalString = ""; // The final string for output.
foreach($id as $key => $value){
$finalString .= '{
"country_id": '.$value.',
"match_type": "exact"
}';
if($key < $numberOfIds-1){
$finalString .= ",";
}
}
$curlStuff = '{
"fields": [
{
"field_type": "countries",
"field_value":[
'.$finalString.'
]
}
]
}';
var_dump($curlStuff);
会给予
string(681) "{
"fields": [
{
"field_type": "countries",
"field_value":[
{
"country_id": 1,
"match_type": "exact"
},{
"country_id": 2,
"match_type": "exact"
},{
"country_id": 3,
"match_type": "exact"
},{
"country_id": 4,
"match_type": "exact"
},{
"country_id": 5,
"match_type": "exact"
},{
"country_id": 6,
"match_type": "exact"
}
]
}
]
}"
因此您可以运行
CURLOPT_POSTFIELDS => $curlStuff;