PHP json_encode将数字编码为字符串 [英] PHP json_encode encoding numbers as strings

查看:212
本文介绍了PHP json_encode将数字编码为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了PHP json_encode函数的一个问题。它将数字编码为字符串,例如

I am having one problem with the PHP json_encode function. It encodes numbers as strings, e.g.

array('id' => 3)

变为

"{ ["id": "3", ...)

当js遇到这些值时,它会将它们解释为字符串,并且数字操作会失败。有没有人知道某种方法来防止 json_encode 从编码数字作为字符串?谢谢!

When js encounters these values, it interprets them as strings and numeric operations fail on them. Does anyone know some way to prevent json_encode from encoding numbers as strings? Thank you!

推荐答案

我做了一个非常快速的测试:

I've done a very quick test :

$a = array(
    'id' => 152,
    'another' => 'test',
    'ananother' => 456,
);
$json = json_encode($a);
echo $json;

这似乎就像你描述的那样,如果我是没错?

This seems to be like what you describe, if I'm not mistaken ?

我得到的是输出:

{"id":152,"another":"test","ananother":456}

因此,在这种情况下,整数尚未转换为字符串。

So, in this case, the integers have not been converted to string.



尽管如此,这可能取决于我们使用的PHP版本:已经纠正了几个与json_encode相关的错误,具体取决于PHP的版本......


Still, this might be dependant of the version of PHP we are using : there have been a couple of json_encode related bugs corrected, depending on the version of PHP...

此测试是使用PHP 5.2.6进行的;我在PHP 5.2.9和5.3.0中得到了同样的东西;我没有其他5.2.x版本可供测试,但是: - (

This test has been made with PHP 5.2.6 ; I'm getting the same thing with PHP 5.2.9 and 5.3.0 ; I don't have another 5.2.x version to test with, though :-(

您使用的是哪个版本的PHP?或者您的测试用例比您发布的示例?

Which version of PHP are you using ? Or is your test-case more complex than the example you posted ?

可能有一个关于 http:/的错误报告/bugs.php.net/ 可能是相关的?例如, Bug#40503 :json_encode整数转换与PHP不一致

Maybe one bug report on http://bugs.php.net/ could be related ? For instance, Bug #40503 : json_encode integer conversion is inconsistent with PHP ?



也许 Bug#38680 也会让你感兴趣,顺便说一下?


Maybe Bug #38680 could interest you too, btw ?

这篇关于PHP json_encode将数字编码为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆