Search code examples
phparrayscurlpostdata

Post Data PHP array in an array


I assume this question is due to my lack of understanding of arrays in PHP.

Generally I am trying to send a post request in php using curl, however I want the postbody to look something like this:

{
   "deliveryAddress":[
      {
         "ID":"5",
         "address":"[email protected]",
         "method":"EMAIL",
         "checkbox":true,
         "flashlight":false
      },
      {
         "ID":"7",
         "address":"[email protected]",
         "method":"EMAIL",
         "checkbox":true,
         "flashlight":false
      }
   ]
}

Is roughly what it looks like in the API, so if I drop this into a program like Fiddler it works perfectly fine. However turning that into the postbody in PHP I have more difficulty. Here is my best attempt so far:

$postData = array(
    'deliveryAddress' => array(
    'ID'=>  '5',
    'address'=>  '[email protected]',
    'method'=>  'EMAIL',
    'checkbox'=>  true,
    'flashlight'=>  false,

    'ID'=>  '7',
    'address'=>  '[email protected]',
    '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);

Clearly I am doing the postdata wrong, but I am not sure how to structure this. Any help would be great. Thank you.


Solution

  • DeliveryAddress is an array of objects (once JSON encoded)

    So if you want to post data according to the JSON you wrote as example then the PHP array has to be built this way:

    $postData = array(
        'deliveryAddress' => array(
    
            array (
                'ID'=>  '5',
                'address'=>  '[email protected]',
                'method'=>  'EMAIL',
                'checkbox'=>  true,
                'flashlight'=>  false
                ),
    
            array (
                'ID'=>  '7',
                'address'=>  '[email protected]',
                'method'=>  'EMAIL',
                'checkbox'=>  true,
                'flashlight'=>  false
            )
    
        )
    );
    

    Note that on the "PHP side" deliveryAddress is now an array of associative arrays (that once json_encoded will turn in an array of objects).