PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 30, 2022

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

 January 30, 2022     json, php, type-conversion, yii2     No comments   

Issue

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();

Solution

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);


Answered By - Muhammad Omer Aslam
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing