简体   繁体   English

将一些json字符串的值转换为php中的整数

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

I have the following php code: 我有以下PHP代码:

$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: 示例JSON如下:

{
 "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”字段设为整数,并将“currency”保留为字符串,以便JSON成为:

 {
 "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. 有什么方法可以使“id”成为整数并将货币作为字符串。

Use Type casting like 使用Type casting

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM