简体   繁体   中英

Converting some values of a json string to an integer in php

I have the following php code:

$data = array(
'id' => $_POST['id'],
'name' => $_POST['name'],
'country' => $_POST['country'],
'currency' => $_POST['currency'],
'description' => $_POST['description']
);

$data_string = json_encode($data);

The sample JSON is as follows:

{
 "id":"7",
 "name":"Dean",
 "country":"US",
 "currency":"840",
 "description":"Test"      
}

I need to make the "id" field an integer only and keep "currency" as a string so that the JSON becomes this:

 {
 "id":7,
 "name":"Dean",
 "country":"US",
 "currency":"840",
 "description":"Test"      
}

I tried using:

$data_string = json_encode($data, JSON_NUMERIC_CHECK);

But it also turns "currency" to an integer.

Is there any way that I can make "id" an integer and leave currency as a string.

Use Type casting like

$data = array(
'id' => (int) $_POST['id'],// type cast
'name' => $_POST['name'],
'country' => $_POST['country'],
'currency' => $_POST['currency'],
'description' => $_POST['description']
);

$data_string = json_encode($data);

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