强制json_encode创建字符串 [英] force json_encode to create strings

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

问题描述

我必须将PHP数组json_encode编码为JavaScript数组.不幸的是,如果我使用的jQuery库包含int而不是字符串,则无法正确处理该数组.

I have to json_encode a PHP array to a JavaScript array. Unfortunately the jQuery library I am using will not properly process that array if it contains ints instead of strings.

大多数情况下,这将产生仅包含字符串的适当数组:

Most of the time, this will produce proper array containing only strings:

json_encode($data)

即使$ data仅包含数字,我通常也会得到它

Even if $data contains just numbers, I usually get this

["3","7","8"]

有时候,我会得到如下结果(注意零):

Sometimes though, I get results like this (note the zero):

["9691","1792","26","1","4","15",0,"1"]

或这个

[16171,15470,10390,7585]

(注意,这显然是不同的数据,以说明正在发生的事情).我需要强制json_encode将数组值视为字符串.我知道有相反的选项JSON_NUMERIC_CHECK强制执行数字.真的不存在等效项吗?似乎我唯一的选择是在JavaScript端再次处理该数组,这虽然可能会在某种程度上破坏对象的封装.

(Note, this is obviously different data to illustrate what's going on). I need to enforce json_encode to treat the array values as strings. I know there's the opposite option JSON_NUMERIC_CHECK which enforces numbers. Does the equivalent really not exist? Seems my only option is to process the array again on the JavaScript end, which, while possible, somewhat breaks the encapsulation of my objects.

推荐答案

如果与JSON_NUMERIC_CHECK相反,那看起来很好,但是看起来不一样.

It would be nice if there was the opposite of JSON_NUMERIC_CHECK but it doesn't look like there is.

为什么在编码之前不能确保数据在php中是正确的类型?

Why can't you ensure the data is of the correct type in your php, before encoding it?

这可能意味着您必须手动将其转换为字符串...

This might mean you have to cast it manually to strings...

这篇关于强制json_encode创建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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