无法通过CURL传递ARRAY?

时间:2018-05-16 21:54:41

标签: php arrays curl arraylist php-curl

$items[] = array("sku"=>"data","name"=>"data","amount"=>0,"qty"=>"0","id"=>"data","price"=>0,"url"=>"data");

$post = array(
'data' => 'data',
            'items' => $items);

$ch = curl_init('urltopost');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 3); //timeout in seconds
header('Content-Type: text/html');
echo curl_exec($ch);

// Check if any error occurred
if(curl_errno($ch))
{
     header('Location: error');
     die();
}

如果我将其发布到自己并执行var_dump($_POST["items"]);,我只会将string(5) "Array"作为输出。

我还尝试了一个不输出数据的foreach循环。

我是愚蠢的,有什么明显的错误吗?

1 个答案:

答案 0 :(得分:0)

你可以试试这个

$post = [];
foreach($items as $index=>$item){
    $new_key = "item[$index]";
    foreach($item as $k=>$v){
        $post[$new_key.'['. $k .']'] = $v;
    }

}
$post['data'] = 'data';

post数组格式为array('key'=>string, ....),不允许数组。如果您想要post数组,则密钥格式为'key[index1][index2] ...'。在服务器中,您将收到$_POST['key']作为数组。