Post数据PHP数组中的数组

Post Data PHP array in an array

我认为这个问题是因为我对PHP中的数组缺乏理解。

通常我尝试使用 curl 在 php 中发送 post 请求,但是我希望 post 正文看起来像这样:

{
   "deliveryAddress":[
      {
         "ID":"5",
         "address":"example@example2.com",
         "method":"EMAIL",
         "checkbox":true,
         "flashlight":false
      },
      {
         "ID":"7",
         "address":"example45@example3.com",
         "method":"EMAIL",
         "checkbox":true,
         "flashlight":false
      }
   ]
}

大致就是它在 API 中的样子,所以如果我将其放入像 Fiddler 这样的程序中,它就可以正常工作。但是,将其转换为 PHP 中的 postbody 我遇到了更多困难。这是我迄今为止最好的尝试:

$postData = array(
    'deliveryAddress' => array(
    'ID'=>  '5',
    'address'=>  'example@example2.com',
    'method'=>  'EMAIL',
    'checkbox'=>  true,
    'flashlight'=>  false,

    'ID'=>  '7',
    'address'=>  'example45@example3.com',
    'method'=>  'EMAIL',
    'checkbox'=>  true,
    'flashlight'=>  false,



    )

);

$url = "ServerIamSendingItTo";
$ch = curl_init();

$headers = array(

    'Content-Type: application/json',
    'Authorization: BASIC (mybase64encodedpass)=='
);





curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_VERBOSE, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

curl_setopt($ch, CURLOPT_URL, $url);



$result = curl_exec($ch);

$ch_error = curl_error($ch);

if ($ch_error) {

   echo"ERROR";
   curl_close($ch);

} else {


     var_dump($result);

}
curl_close($ch);

显然我做的 post 数据有误,但我不确定如何构建它。任何帮助都会很棒。谢谢。

DeliveryAddress 是一个对象数组(一旦 JSON 编码)

因此,如果您想根据您作为示例编写的 JSON post 数据,则必须以这种方式构建 PHP 数组:

$postData = array(
    'deliveryAddress' => array(

        array (
            'ID'=>  '5',
            'address'=>  'example@example2.com',
            'method'=>  'EMAIL',
            'checkbox'=>  true,
            'flashlight'=>  false
            ),

        array (
            'ID'=>  '7',
            'address'=>  'example45@example3.com',
            'method'=>  'EMAIL',
            'checkbox'=>  true,
            'flashlight'=>  false
        )

    )
);

请注意 "PHP side" deliveryAddress 现在是一个关联数组的数组(一旦 json_encoded 将变成一个对象数组)。