我一直试图调试这个..我通过cURL将多维数组传递给另一个脚本,我想在传递curl执行后对该数组做一些事情.但是看起来在数组通过curl之后(至少它的副本),原始数组搞砸了!
$myarray[0]['name'] = "TJ";
$myarray[0]['age'] = "21";
$myarray[0]['sex'] = "yes please";
printr($myarray); //outputs the array properly
//upload the array data as-is to central
// Get cURL resource
$curl = curl_init();
// Set some options for cURL
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://localhost/projects/sync_dtr.php?',
CURLOPT_USERAGENT => 'TK local code: blq ',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $myarray
));
// Send the request & save response to $resp
$response = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
printr($myarray); //doesn't output the array properly, instead it outputs "Array ( [0] => Array ) "
Run Code Online (Sandbox Code Playgroud)
这是一个错误或预期的结果/效果?我不明白cURL如何编写/修改原始数组.即使我制作了$ myarray的副本,并在cURL中使用了一个副本,机器人副本也搞砸了!
但如果我不使用多维数组,一切似乎都没问题.
内部发生的是每个顶部数组元素变成一个字符串 ; 遗憾的是,这是在不应用写时复制语义的情况下执行的.我不会把这个称为bug,但它肯定是不直观的.
也就是说,CURLOPT_POSTFIELDS不应该用于多维价值; 相反,使用http_build_query():
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
'myarray' => $myarray
)));
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我确保顶级元素是一个字符串; 这对于url编码的表单值是必要的.