Quantcast
Channel: json_encode change number into string - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by dave for json_encode change number into string

$
0
0

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}
?>

Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>