簡體   English   中英

將一些json字符串的值轉換為php中的整數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM