Convert some json string values ​​to 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 JSON sample is as follows:

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

I need to make the "id" field integer and save the "currency" as a string so that JSON becomes the following:

  { "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 the "currency" into an integer.

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

+7
json arrays php
source share
1 answer

Use Type casting as

 $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); 
+6
source share

All Articles