手机拨号上网-office 2007

json_decode
2023年4月4日发(作者:3dsmax中文版)

php精度丢失,PHPjson_decode精度丢失问题!

#PHPjson_decode精度丢失问题!

今天在群⾥⾯,有⼈说php在很长的数字丢失问题如下⾯json串

$str='{"errcode":0,"errmsg":"ok","department":

[{"id":8559795,"name":"test12345","parentid":8559795,"order":1},

{"id":8559795,"name":"test","parentid":8559795,"order":1}]}';

var_dump(json_decode($str,true));

得出来的结果如图

诶,怎么精度丢失了,看id和parentid。都变成float(8.5597950095881E+18)

解决办法

请看⼿册

json_decode

(PHP5>=5.2.0,PECLjson>=1.2.0,PHP7)

json_decode—对JSON格式的字符串进⾏编码

说明

mixedjson_decode(string$json[,bool$assoc=false[,int$depth=512[,int$options=0]]])

接受⼀个JSON格式的字符串并且把它转换为PHP变量

参数

json

待解码的jsonstring格式的字符串。

ThisfunctiononlyworkswithUTF-8encodeddata.

assoc

当该参数为TRUE时,将返回array⽽⾮object。

depth

Userspecifiedrecursiondepth.

options

tlyonlyJSON_BIGINT_AS_STRINGissupported(defaultistocastlargeintegersas

floats)

看第四个参数

**options**

tlyonlyJSON_BIGINT_AS_STRINGissupporteddefaultistocastlargeintegersas

floats

翻译:JSON解码选项的位掩码。⽬前只⽀持JSON_BIGINT_AS_STRING默认将⼤型整数转换为浮点数

解决⽅式

$str='{"errcode":0,"errmsg":"ok","department":

[{"id":8559795,"name":"test12345","parentid":8559795,"order":1},

{"id":8559795,"name":"test","parentid":8559795,"order":1}]}';

var_dump(json_decode($str,true,512,JSON_BIGINT_AS_STRING););

得出来的结果⾃⼰测试

要养成良好的翻⼿册的习惯,php如果在低版本出现这种bug,我相信,但是现在都到7了。这种问题应该很早就会修复的!

更多推荐

json_decode