强制PHP json_encode()将索引编码为字符串 [英] Force PHP json_encode() to encode indexes as strings

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

问题描述

我有一个数组设置,如下所示:

I have a an array setup as follows:

$myArray = array();
$myArray[] = "New array item 1";
$myArray[] = "New array item 2";
$myArray[] = "New array item 3";

当我在其上运行json_encode()时,它会输出以下内容:

When I run json_encode() on it it outputs the following:

["New array item 1","New array item 2","New array item 3"]

我想要的功能是将索引编码为字符串:

What I want is for the function to encode the indexes as strings:

{"0":"New array item 1","1":"New array item 2","2":"New array item 3"}

这样以后我就可以删除第一个项目而不会影响第二个项目的索引.

So that later I can remove say the first item without affecting the index of the second.

有一种简单的方法吗?

推荐答案

使用JSON_FORCE_OBJECT:

json_encode( $data, JSON_FORCE_OBJECT );

需要PHP 5.3 +

Requires PHP 5.3+

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

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