deantaz deantaz - 3 months ago 17
JSON Question

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.

Answer

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