简体   繁体   中英

Create JSON object with multiple values inside an array in PHP

I am working with Acuity Scheduling API and in order to post a custom field, I need to have a JSON object inside of the array that has 2 key/pair values, id and value. Here is my current code for this:

 $postarray = array (
        'datetime'=>'2017-02-01T14:00:00-0800',         
        'appointmentTypeID'=>'Appt ID',
        'firstName'=>'First Name',
        'lastName'=>'last Name',
        'email'=>'myemail',
        'phone'=>'phone #',
        'fields' => array(
        array('id'=>'1234', 'value'=>'Field Data')
        )
);

$post = json_encode($postarray);

I have an array inside of the 'fields' array because I don't know how to add a json object with 2 values inside of an array that will then go through json_encode, as the request requires that it be converted to JSON first before being sent.

It is currently giving me this error: "{"status_code":400,"message":"The intake form field "1234" does not exist on this appointment." Where after "u0022" it adds on my field id. What I need is for my main array to become a JSON Object, the 'fields' to be an array, then the individual id and value pairs to be their own objects, like so (Taken Directly from Acuity Scheduling API):

 {
  "datetime": "2016-02-03T14:00:00-0800",
  "appointmentTypeID": 1,
  "firstName": "Bob",
  "lastName": "McTest",
  "email": "bob.mctest@example.com",
  "certificate": "ABC123",
  "fields": [
    {"id": 1, "value": "Party time!"}
  ]
}

Here is Acuity Scheduling API for reference on this particular request, https://developers.acuityscheduling.com/reference#post-appointments

'fields' => array(
     json_encode(array('id'=>'1234', 'value'=>'Field Data'))
)

The ID should be a number, not a string, so don't put it in quotes.

$postarray = array (
    'datetime'=>'2017-02-01T14:00:00-0800',         
    'appointmentTypeID'=>'Appt ID',
    'firstName'=>'First Name',
    'lastName'=>'last Name',
    'email'=>'myemail',
    'phone'=>'phone #',
    'fields' => array(
        array('id'=> 1234, 'value'=>'Field Data')
    )
);

If you're getting the ID from a script parameter, use intval() to convert it from a string to a number.

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