json_encode change number into string

arrays, cakephp-2.3, json

Solution

I am guessing online you have an older version of PHP:

JSON_NUMERIC_CHECK (integer)

Encodes numeric strings as numbers. Available since PHP 5.3.3.

When you JSON encode, it will not have quotes if PHP knows it is not a string. If you need to do it manually, you could do something like this:

<?php

  function json_numeric($array)
  {
     if (is_array($array) || is_object($array)) {
        foreach($array as &$prop) {
            if (is_numeric($prop)) {
                $prop = intval($prop);
            }
            if (is_object($prop) || is_array($prop)) {
                $prop = json_numeric($prop);
            }
        }
     }
     return $array;
  }

  $x = array("a" => 1, "b" => "2", "c"=>array("d"=>1, "e"=>"2"));
  echo json_encode(json_numeric($x));
  //{"a":1,"b":2,"c":{"d":1,"e":2}}
  $y = new stdClass();
  $y->a = 1;
  $y->b = "2";
  echo json_encode(json_numeric($y));
  //{"a":1,"b":2}
?>

Problem

I have an array which has some strings values and some numeric values. I used ``` json_encode ``` to convert array into json array but it convert numbers values into string which I do not want. ``` [["India","2"],["Panama","1"]] ``` I tried ``` JSON_NUMERIC_CHECK ``` as second parameter in json_encode then it works fine on localhost but showing error online. ``` Use of undefined constant JSON_NUMERIC_CHECK - assumed ' ``` I am using cakephp 2.3

Original source