简介
因此,我试图将表单值作为查询字符串发送到API。 API需要这样的查询字符串:
&name=Charles+Hansen&[email protected]&locations=23433&locations=23231&propertyTypes=APARTMENT&propertyTypes=TOWNHOUSE&message=test"
您可以看到,有多个“ propertyTypes”和“ locations”,这取决于用户在表单中选择了多少个属性类型或位置。因此,我将所有$ _POST数据存储在一个如下所示的多维数组中,因为我显然不能拥有多个具有相同名称“ propertyTypes”或“ locations”的键:
Array
(
[name] => Charles Hansen
[email] => [email protected]
[locations] => Array
(
[0] => 23433
[1] => 23231
)
[propertyTypes] => Array
(
[0] => APARTMENT
[1] => TOWNHOUSE
)
[message] => test
)
cURL不支持多维数组,因此,在使用它之前,我首先要自己构建查询。这是我的cURL函数:
function sg_order($post_fields) {
if($post_fields) {
$query = http_build_query($post_fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/order?orgKey=' . constant('ORG_KEY'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: ' . strlen($query))
);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch)) {
error_log('Curl error: ' . curl_error($ch) . $result);
}else{
error_log('Curl response: ' . $status);
}
curl_close($ch);
return $result;
}
}
orgKey
是验证所必需的参数。
问题
我的问题是,由$query = http_build_query($post_fields);
构建的查询包含嵌套数组的键([0],[1]等)。 $query
的结果如下所示:
&name=Charles+Hansen&[email protected]&locations[0]=23433&locations[1]=23231&propertyTypes[0]=APARTMENT&propertyTypes[1]=TOWNHOUSE&message=test"
如何摆脱键([0],[1]等),以便查询看起来与API期望的完全一样?
其他信息
如果您不想编写自己的http_build_query版本,那么我建议您根据手册http://php.net/manual/en/function.http-build-query.php#111819中的此用户注释修改版本。
$query = http_build_query($query); $query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
他们在这里用
foo[xy]
替换foo[]
-因为您也不想保留[]
,只需将preg_replace调用中的'%5B%5D'
替换为空字符串。