简体   繁体   中英

How to add children to JSON HTTP POST request with PHP & cURL

I'm connecting to a third party web service and need to be able to send JSON to the service.

I've configured everything ok, and I can send up basic JSON nodes, but where I am struggling is trying to send up child data of a top level node.

So, for example, I want to send...

“children_count”: 1,
“infants_count”: 0
“stay_dates”: [{
    “date”: “2015­01­02”,
    “rate_id”: 2,
    “room_type_id”: 2,
    “adults_count”: 2,
    “children_count”: 1,
    “infants_count”: 0
    }],

Under 'stay_dates' are the children I need to send up.

How do I send this with PHP?

This is my method so far, with the child pieces missing. Any help would be gratefully received!

// The data to send to the API
$postData = array(
    'children_count' => 1,
    'infants_count' => 0,
    // stay_dates to go in here

);

// Setup cURL
$ch = curl_init('https://www.webservice.com');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        //'Authorization: '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

Many thanks!

In JSON {} stands for object:

$stayDate = new stdClass(); //down-vote is in order
$stayDate->date = “2015­01­02”;
$stayDate->rate_id = 2;
$stayDate->room_type_id = 2;
$stayDate->adults_count = 2;
$stayDate->children_count = 1;
$stayDate->infants_count = 0;
$postData = array(
    'children_count' => 1,
    'infants_count' => 0,
    'stay_dates' = [$stayDate]
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM