将 PHP 中 JSON 字符串中的某些值转换为整数

7

我有以下的php代码:

$data = array(
'id' => $_POST['id'],
'name' => $_POST['name'],
'country' => $_POST['country'],
'currency' => $_POST['currency'],
'description' => $_POST['description']
);

$data_string = json_encode($data);

示例JSON如下:
{
 "id":"7",
 "name":"Dean",
 "country":"US",
 "currency":"840",
 "description":"Test"      
}

我需要将“id”字段仅设为整数,并保持“currency”为字符串,以使JSON变成这样:
 {
 "id":7,
 "name":"Dean",
 "country":"US",
 "currency":"840",
 "description":"Test"      
}

我尝试使用:

$data_string = json_encode($data, JSON_NUMERIC_CHECK);

但是它也会把“货币”转换为整数。

有没有办法让“id”成为整数,而让“currency”保持为字符串呢?


尝试使用我的答案来解决你的问题。 - Passionate Coder
1个回答

8

使用类型转换,例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接