介绍
因此,我正在尝试将表单值作为查询字符串发送到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/zh/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[]
在这里-因为你不希望保留[]
或者,只需更换'%5B%5D'
与一个空字符串,而不是preg_replace函数调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句