使用json_encode()的引号中的数字 [英] Numbers in quotes using json_encode()

查看:526
本文介绍了使用json_encode()的引号中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

各种第三方公司都在强迫我们使用非常规代码并产生非标准输出.

Various 3rd party companies are forcing us to use non-conventional code and produce non-standard output.

我们正在使用标准的json_encode()在JS/HTML中输出一个JSON变量,如下所示:

We are using standard json_encode() to output a JSON variable in JS/HTML which looks like:

"custom":{"1":2,"2":7,"3":5}

现在他们告诉我们这对他们不起作用,他们需要这种方式:

Now they tell us this isn't working for them, they need it this way:

"custom":{"1":"2","2":"7","3":"5"}

我可以强制PHP用引号引起来的环绕数字吗?在编码之前构建对象时也许使用强制转换(string)?

Can I force PHP to wrap quotes arround numbers? Maybe using cast (string) when we build the object before encoding?

主要,我们需要与以下选项bitflag相反:

Mainly, we need an opposite of the following option bitflag:

JSON_NUMERIC_CHECK (integer)

JSON_NUMERIC_CHECK (integer)

Encodes numeric strings as numbers. Available since PHP 5.3.3.

但是我怀疑这个存在.

推荐答案

猜想您需要自己解决此问题.我想不出内置函数,但是您可以编写自己的函数:

Guess you need to fix this yourself. I can't think of a built-in function, but you can write your own:

function stringify_numbers($obj) {
    foreach($obj as &$item)
        if(is_object($item) || is_array($item))
            $item = stringify_numbers($item); // recurse!
        if(is_numeric($item)
            $item = (string)$item;
    return $obj;
}

现在您可以使用json_encode(stringify_numbers($yourObject))

这篇关于使用json_encode()的引号中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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