在使用 PHP cURL 發送 POST 請求時,若資料為多維陣列需先扁平化為 key[subkey]=value 格式,方能被遠端伺服器正確解析(如 PHP 端 $_POST 自動解析)。
<?php
/**
* 多維陣列轉換為支援 cURL 提交的一維陣列
* @param array $params 待轉換陣列
* @param string $pre 遞迴用前綴鍵名
* @return array 扁平化後的關聯陣列
*/
function toPost(array $params = [], $pre = '') {
$result = [];
foreach ($params as $key => $val) {
if (is_array($val)) {
// 遞迴處理子陣列,構建新前綴:parent[child]
$subPre = ($pre === '') ? $key : $pre . '[' . $key . ']';
$result = array_merge($result, toPost($val, $subPre));
} else {
// 葉子節點,直接組合鍵名
$result[$pre . '[' . $key . ']'] = $val;
}
}
return $result;
}
<?php
$data = [
'user' => [
'name' => 'John',
'contact' => [
'email' => 'john@example.com',
'phone' => '1234567890'
]
],
'action' => 'register'
];
$postData = toPost($data);
/*
結果:
[
'user[name]' => 'John',
'user[contact][email]' => 'john@example.com',
'user[contact][phone]' => '1234567890',
'action' => 'register'
]
*/
// cURL 發送
$ch = curl_init('https://api.example.com/endpoint');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 或直接傳陣列
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$pre 參數逐層疊加 [key] 結構。array_merge 將各層級結果扁平化。[ ]),否則解析時會產生歧義。CURLFile),需額外處理,不可直接扁平化。[] 簡化程式碼。