简体   繁体   中英

Php Json Data format

There is a curl POST request example sent via REST JSON.

{"email": "sam@email.com", "items": [{ "name": "api Name", "quantity": 10, "unit_price": 2}, { "name": "api 2", "quantity": "4", "unit_price": 3 }] 

}

How can I format this in PHP.

I have tried the following:

$data = array(
        'email' => 'john@dow.com', 
        );
$data['items'] = array(
        'name' => 'fruits', 'quantity' => 4,
         'unit_price' => 7,
        );

The service just accepts email , and ignores items .

the items array is an array of objects. You are showing an map of strings

An easy trick is to use the PHP function json_decode() to get a PHP data structure that, when passed to json_encode() produces the string you need:

var_export(json_decode(
    '{"email": "sam@email.com", "items": [{ "name": "api Name", "quantity": 10, "unit_price": 2}, { "name": "api 2", "quantity": "4", "unit_price": 3 }]}',
    TRUE
));

produces:

array(
    'email' => 'sam@email.com',
    'items' => array(
        0 => array(
            'name' => 'api Name',
            'quantity' => 10,
            'unit_price' => 2,
        ),
        1 => array(
            'name' => 'api 2',
            'quantity' => '4',
            'unit_price' => 3,
        ),
    ),
)

Pass TRUE as the second argument to get arrays back; without it, json_decode() generates objects instead of associative arrays.

Use function var_export() to get the PHP code that generates the data structure you pass it as argument.

Use the code above in a separate script, to get a hint about the data structure you need to create in order to get the desired string when you encode it as JSON. Don't put it into the product you develop.

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