我尝试通过 cURL
发送多数组,但找不到好的方法。
我的代码示例:
$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
这将起作用并在 curl_init()
站点上给出我想要的结果:
print_r( $_POST )
:
Array (
[a] => testa
[b] => testb
[c] => Array (
[d] => test1
[e] => test2
)
)
我想动态添加 c 数组,如下所示:
$c['d'] = 'test1';
$c['e'] = 'test2';
但是,如果我尝试使用 array_push
或 []
添加数组,我总是会在没有数据的数组中得到 and (string)Array 。
谁能帮我做一下吗?
用于更快测试的完整代码:
$url = 'url_to_test.php';
$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' );
$ch = curl_init($url);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$buffer = curl_exec ($ch);
curl_close ($ch);
echo $buffer;
测试.php
print_r($_POST);
感谢您的帮助!
干杯
最佳答案
在
$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' )
您只是添加了新的字符串键“c[d]”和“c[e]”。
如果您想要嵌套数组,请使用:
$data = array( 'a' => 'testa', 'b' => 'testb', 'c' =>
array( 'd' => 'test1', 'e' => 'test2' )
)
-- 编辑--
您正在尝试设置 POST 数据,它本质上是一组键值对。您无法提供嵌套数组。但是,您可以序列化嵌套数组并在另一端对其进行解码。例如:
$post_data = array('data' => serialize($data));
在接收端:
$data = unserialize($_POST['data']);
关于php - (PHP) $_POST + cURL + 多数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7508349/