首页 > 解决方案 > 序列化为 JSON 时 PHP 中的意外行为

问题描述

PHP 7.3.15 拉拉维尔 5.8.38

dump(ini_get('serialize_precision'));
// Out: "-1"

$data = DB::table('SOME QUERY HERE')->get();
dump($data);
 #items: array:10 [
    0 => {#713
      +"creation": "2020-04-23 04:00:00"
      +"user_name": "Some Client"
      +"amount": 17.8
      +"count": 3
    }

dump(json_encode($data, JSON_PRETTY_PRINT));
[
    {
        "creation": "2020-04-23 04:00:00",
        "user_name": "Some Client",
        "amount": 17.799999999999997 // Why?
        "count": 3
    }

我在这里做错了什么?当我将 JSON 格式的数据发送到我的 Javascript 客户端时,我需要同样的精度。

提前致谢。

更新 我已经这样做了:

ini_set("serialize_precision", -1);

但这有效:

dump(json_encode([1002.31, 2002.42]));
// Out: "[1002.31,2002.42]"

似乎问题出在序列化 Laravel 集合时?

标签: phpjsonlaravel

解决方案


推荐阅读