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.
To convert string to integer using PHP built-in function, intval(), provide the string as argument to the function. The function will return the integer value corresponding to the string content. $int_value = intval( $string );
Use json_decode() Function to Extract Data From JSON in PHP. We will use the built-in function json_decode() to extract data from JSON. We will convert the JSON string to an object or an array to extract the data. The correct syntax to use this function is as follows.
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With