7

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.

1

1 Answer 1

8

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.