顯然,無窮大和NaN不是JSON規範的一部分,所以這個PHP代碼:PHP:如何將無限或NaN編號編碼爲JSON?
$numbers = array();
$numbers ['positive_infinity'] = +INF;
$numbers ['negative_infinity'] = -INF;
$numbers ['not_a_number'] = NAN;
$array_print = print_r ($numbers, true);
$array_json = json_encode ($numbers);
echo "\nprint_r(): $array_print";
echo "\njson_encode(): $array_json";
產生以下:
PHP Warning: json_encode(): double INF does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8
PHP Warning: json_encode(): double -INF does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8
PHP Warning: json_encode(): double NAN does not conform to the JSON spec, encoded as 0 in /home/septi/test.php on line 8
print_r(): Array
(
[positive_infinity] => INF
[negative_infinity] => -INF
[not_a_number] => NAN
)
json_encode(): {"positive_infinity":0,"negative_infinity":0,"not_a_number":0}
有沒有辦法正確編碼,這些數字沒有寫我自己json_encode()
功能?也許有一些解決方法?
+1引用規範和提及文字。然而接受另一個答案,因爲它建議了將它們轉換回數字的方式。 – Septagram