问题
I am using Yii2 framework to create this JSON array:
"data": [
{
"id": 201,
"name": "John",
"age": "30"
}
]
The age is a string and I need it to be an integer, that is, without quotation marks. Like this:
"data": [
{
"id": 201,
"name": "John",
"age": 30
}
]
This is the PHP function that create the JSON array:
$persons['data'] = Persons::find()
->select([
'id',
'name',
'age'
])
->asArray()
->all();
回答1:
You can use JSON_NUMERIC_CHECK
flag as second parameter of json_encode()
or \yii\helpers\Json::encode()
for converting numbers automatically since php 5.3, see here.
You can use the flag like
$data = Persons::find()
->select(
[
'id',
'name',
'age'
]
)
->asArray()
->all();
$json = \yii\helpers\Json::encode($data,JSON_NUMERIC_CHECK);
来源:https://stackoverflow.com/questions/51770766/yii2-how-to-convert-data-type-value-of-a-json-php-array