This is a bit like the mysql int type overflows when it exceeds, and we only need to use bigint. Then because of the problem of int data range in php, this kind of problem may also occur.
An error was encountered during the encoding process, that is, when processing json, the data of large int values was damaged after decoding, such as:
The code is as follows
代码如下 |
复制代码 |
$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)
}
|
|
Copy code
|
代码如下 |
复制代码 |
array(2) {
["id1"]=>int(2147483647)
["id2"]=>int(-2147483646)
}
|
$array = array(
"id1" => 2147483647,
"id2" => 2147483648
);
$json = json_encode($array);
代码如下 |
复制代码 |
$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) |
$out = json_decode($json, true);
var_dump($out);
Theoretically you should see:
array(2) {
["id1"]=>int(2147483647)
代码如下 |
复制代码 |
$array = array(
"id1" => 2147483647,
"id2" => 2147483648
);
$json = json_encode($array);
$json = preg_replace('/("idd":)(d{9,})/i', '""', $json);
$out = json_decode($json, true);
var_dump($out);
|
["id2"]=>int(2147483648)
}
|
But actually on my computer I get:
This is determined by the PHP integer value range, which is operating system dependent. On 32-bit operating systems, PHP's maximum integer value is 2147483647, which you can see by outputting PHP_INT_MAX.
Generally, if you assign a large number, PHP will automatically determine the range of the value and automatically convert the type, such as:
However, this detection is not performed in the json_decode method. This is a bug of PHP (old version). In versions after 5.3, this problem does not exist.
If you don’t want to update your PHP, there is another way, which is to convert the number into a string. Let’s take the above code as an example:
The code is as follows
|
Copy code
|
$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);
Of course, how to replace this depends on the needs, and requires more detailed testing.
http://www.bkjia.com/PHPjc/632266.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632266.htmlTechArticleThis is a bit like the mysql int type overflows when it exceeds, and we only need to use bigint, so because in php There is a problem with the int data range, so this kind of problem may also occur. Encoding...
|