json_decode 整型溢出解决方法
编码过程中遇到个错误,就是在处理json时,数值较大的int值在解码后数据被损坏,比如:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy3508')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy3508>$array = array(
"id1" => 2147483647,
"id2" => 2147483648
);
$json = json_encode($array);
$out = json_decode($json, true);
var_dump($out);
理论上应该看到:
array(2) {
["id1"]=>int(2147483647)
["id2"]=>int(2147483648)
}
但实际在我的电脑上却得到:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9339')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy9339>array(2) {["id1"]=>int(2147483647)
["id2"]=>int(-2147483646)
}
这是由PHP整数值范围决定的,而这个范围依赖于操作系统。在32位操作系统中,PHP的整数最大值是2147483647,你可以通过输出PHP_INT_MAX看到。
一般情况下,你赋值一个很大的数,PHP会自动判定这个数值的范围并自动转换类型,如:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy2971')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy2971>$large_number = 2147483647;var_dump($large_number); // int(2147483647)
$large_number = 2147483648;
var_dump($large_number); // float(2147483648)
$million = 1000000;
$large_number = 50000 * $million;
var_dump($large_number); // float(50000000000)
但是在json_decode方法中没有进行这种检测,这是PHP(旧版本)的bug,在5.3以后的版本,就不存在这个问题了。
如果你不想更新你的PHP,那还有个办法,就是将数字转为字符串。还是以上面的代码为例:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy1197')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy1197>$array = array("id1" => 2147483647,
"id2" => 2147483648
);
$json = json_encode($array);
$json = preg_replace('/("idd":)(d{9,})/i', '${1}"${2}"', $json);
$out = json_decode($json, true);
var_dump($out);
当然,这个怎么替换是按需而定的,而且需要比较细致的测试。
您可能感兴趣的文章:
json_decode 整型溢出解决方法
解决mysql无符号整型自减运算时溢出的问题
C语言的数据类型整型溢出
IE6下溢出多余文字解决方案Iebug
PHP JSON转数组
php下载文件的问题分析
分享文字溢出隐藏实例
php中如何使用json_decode()和json_encode()?
PHP Fatal error: Cannot use object of type stdClass as array in错误
Golang map底层实现原理解析