Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

arrays

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.

like image 844
deantawonezvi Avatar asked Sep 02 '16 08:09

deantawonezvi


People also ask

How do I convert a string to an integer in PHP?

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 );

How do I extract data from JSON with PHP?

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.

What is json_encode and json_decode in PHP?

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.

How can I convert JSON to string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);


1 Answers

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);
like image 183
Passionate Coder Avatar answered Oct 09 '22 07:10

Passionate Coder