PHP json_decode 精度丢失问题!

#PHP json_decode 精度丢失问题!

今天在群里面,有人说php在很长的数字丢失问题如下面json串

<?php 
$str = '{"errcode":0,"errmsg":"ok","department":[{"id":8559795009588101021,"name":"test12345","parentid":8559795009588100870,"order":1},{"id":8559795009588100880,"name":"test","parentid":8559795009588100870,"order":1}]}';

var_dump(json_decode($str,true));
得出来的结果如图

精度丢失

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

解决办法

请看手册

  • json_decode
    (PHP 5 >= 5.2.0, PECL json >= 1.2.0, PHP 7)
    json_decode — 对 JSON 格式的字符串进行编码
    说明
    mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
    接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
    参数
    json
    待解码的 json string 格式的字符串。
    This function only works with UTF-8 encoded data.
    assoc
    当该参数为 TRUE 时,将返回 array 而非 object 。
    depth
    User specified recursion depth.
    options
    Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)

看第四个参数
**options **
Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported default is to cast large integers as floats

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

解决方式

<?php 
$str = '{"errcode":0,"errmsg":"ok","department":[{"id":8559795009588101021,"name":"test12345","parentid":8559795009588100870,"order":1},{"id":8559795009588100880,"name":"test","parentid":8559795009588100870,"order":1}]}';

var_dump(json_decode($str,true,512,JSON_BIGINT_AS_STRING););
得出来的结果自己测试

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

posted @ 2019-06-26 11:27  余农场主  阅读(905)  评论(0)    收藏  举报