[英]Converting some values of a json string to an integer in php
我有以下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”成為整數並將貨幣作為字符串。
使用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.