Yii2: How to convert data type value of a JSON PHP array?

≡放荡痞女 提交于 2021-02-10 15:29:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!