php json_decode 后,数字转换成了 科学计数法 的解决方案 (number_format 函数改变了原有的值)

来源:互联网 发布:销售软件定制 编辑:程序博客网 时间:2024/05/15 06:25

php在执行 json_decode 后,数字对象转换成了 科学计数法

    "result":[{"uid":1021696035257980469,"categoryUid":1502187334502418450}]

这是获取到的 json串,直接使用 json_decode 之后,变成科学计数法

结果:

    ["uid"] => float(1.021696035258E+18)    ["categoryUid"] => float(1.5021873345024E+18)

解决问题

 1. 第一种方法使用 php自带函数 number_format(),效果如下:
    $json = '{"uid":1021696035257980469,"categoryUid":1502187334502418450}';    $array = $this->json_decode($json,TRUE);    foreach ($arrayas $key => $val) {        $array[$key] = number_format($val, 0, '', '');    }    print_r($array);

结果:

    ["uid"] => string(19) "1021696035257980416"    ["categoryUid"] => string(19) "1502187334502418432"

这时候发现得到的数据与原有数据不一致,结果被改变,此方法暂时行不通。

 2. 第二种方法,后来去网上查了 json_decode 函数,发现json_decode 支持大数直接转为 string 的。

函数链接地址: http://php.net/manual/en/function.json-decode.php

  • The first is JSON_BIGINT_AS_STRING that allows casting big
    integers to string instead of floats which is the default.
  • 允许将大整数转换成字符串而不是浮点数
    $json = '{"uid":1021696035257980469,"categoryUid":1502187334502418450}';    $array = $this->json_decode($json, TRUE, 512, JSON_BIGINT_AS_STRING);    print_r($array);

到了正确的结果:

    ["uid"] => string(19) "1021696035257980469"    ["categoryUid"] => string(19) "1502187334502418450"
阅读全文
0 0
原创粉丝点击