PHP curl_setopt($ch, CURLOPT_POSTFIELDS, $data) 當 $data 為數組時,會自動編碼為 multipart/form-data 或 application/x-www-form-urlencoded。但某些 API 要求嚴格的扁平鍵值對(如 user[name]=John&user[age]=30),需手動將多維數組展開。
<?php
/**
* 多維數組轉換為支援 CURL 提交的一維數組(帶方括號鍵名)
*
* @param array $params 待轉換數組
* @param string $prefix 遞歸前綴(內部使用)
* @return array 扁平化後的鍵值對數組
*/
function flattenArrayForCurl(array $params, string $prefix = ''): array
{
$result = [];
foreach ($params as $key => $value) {
// 構建新鍵名:prefix[key] 或 key
$newKey = $prefix ? "{$prefix}[{$key}]" : $key;
if (is_array($value)) {
// 遞歸處理子數組
$result = array_merge($result, flattenArrayForCurl($value, $newKey));
} else {
// 標量值直接賦值
$result[$newKey] = $value;
}
}
return $result;
}
// 使用示例
$nested = [
'user' => [
'name' => '張三',
'age' => 28,
'address' => [
'city' => '北京',
'district' => '朝陽區',
'tags' => ['vip', 'developer'], // 索引數組將變為 tags[0], tags[1]
],
],
'action' => 'register',
'source' => 'web',
];
$flat = flattenArrayForCurl($nested);
/*
結果:
[
'user[name]' => '張三',
'user[age]' => 28,
'user[address][city]' => '北京',
'user[address][district]' => '朝陽區',
'user[address][tags][0]' => 'vip',
'user[address][tags][1]' => 'developer',
'action' => 'register',
'source' => 'web',
]
*/
// 直接傳給 CURL(自動編碼為 application/x-www-form-urlencoded)
$ch = curl_init('https://api.example.com/endpoint');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $flat, // 扁平數組
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
]);
$response = curl_exec($ch);
curl_close($ch);
?>
<?php
function flattenArrayForCurlAdvanced(array $params, string $prefix = ''): array
{
$result = [];
foreach ($params as $key => $value) {
$newKey = $prefix ? "{$prefix}[{$key}]" : $key;
if (is_array($value)) {
// 檢測是否為 CURLFile 對象數組(文件上傳)
if (count($value) === 1 && $value[0] instanceof \CURLFile) {
$result[$newKey] = $value[0];
} else {
$result = array_merge($result, flattenArrayForCurlAdvanced($value, $newKey));
}
} elseif ($value instanceof \CURLFile) {
$result[$newKey] = $value;
} else {
$result[$newKey] = $value;
}
}
return $result;
}
// 文件上傳示例
$postData = [
'user' => ['avatar' => [new \CURLFile('/path/to/avatar.jpg', 'image/jpeg', 'avatar.jpg')]],
'action' => 'upload_avatar',
];
$flat = flattenArrayForCurlAdvanced($postData);
// 此時 $flat['user[avatar]'] 為 CURLFile 對象,CURL 會自動構建 multipart/form-data
?>
<?php
// PHP 內建函數自動處理多維數組編碼為 a[b][c]=val 格式
$queryString = http_build_query($nested);
// 結果: user%5Bname%5D=%E5%BC%A0%E4%B8%89&user%5Bage%5D=28&user%5Baddress%5D%5Bcity%5D=%E5%8C%97%E4%BA%AC...
// 直接用於 CURLOPT_POSTFIELDS(字符串模式)
curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString);
// 需顯式設置 Content-Type
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
?>
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 自定義遞歸扁平化 | 完全可控鍵名格式、支援 CURLFile 混合、便於調試檢查 | 需維護代碼 | 複雜表單、文件上傳混合、需精確控制鍵名 |
| http_build_query() | 零依賴、性能好、標準 RFC 3986 編碼 | 難以混合 CURLFile、鍵名編碼後不可讀 | 純鍵值對提交、無文件上傳 |
| 直接傳多維數組 | 代碼最少 | CURL 自動判斷為 multipart/form-data,某些 API 拒絕 | 簡單場景、對方接受 multipart |
http_build_query() 簡潔高效。CURLFile 對象。Content-Type 與鍵名格式(是否帶方括號、是否 URL 編碼)。