php - (PHP) $_POST + cURL + 多数组

标签 php curl multidimensional-array http-post array-push

我尝试通过 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/

相关文章:

php - 当我从 View 表中获取数据时出现 Laravel 错误

linux - bash | curl | curl 2 个 URL 然后停止

c++ - 在 C++ 函数中使用 CURL

f# - F#多维数组类型

ruby - 有没有一种简单的方法可以在 Ruby 中复制多维数组?

php - 如何在mysql中选择前三行

php - 如何构建 PHP 依赖注入(inject)容器

php - InnoDB/phpmyadmin 问题

java - 我想在 PHP 中集成 Aadhaar 卡身份验证。我尝试使用此代码进行 API 访问,但无法得到任何响应

python - Numpy 深拷贝仍在改变原始数组