1

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();
2
  • can you use Int($age), before make json? Commented Aug 9, 2018 at 15:28
  • 1/ Can you change it BEFORE creating the JSON array? 2/ Where do you need it to be an integer and not a string? You can maybe change it juste BEFORE using it too. 3/ If you can't do it in my 1/ or 2/, maybe try some json_decode($array), transform the string in int then json_encode($array) to get your array as before. Commented Aug 9, 2018 at 15:31

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

Comments

0

JSON_NUMERIC_CHECK would make name etc also int if Integer is saved in those fields. I am assuming this is in context or rest api. You can override the fields() in your model.

public function fields()
{
    $fields = parent::fields();
    $fields['someProperty'] = function ($model) {
        
        return $model->someOtherProperty + something etc;
    };
    return $fields;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.