PHP数组unset()之后,PHP json_encode作为对象 [英] PHP json_encode as object after PHP array unset()
问题描述
使用unset
删除数字数组键后,我遇到了json_encode
的奇怪行为.下面的代码应该使问题清楚.我已经从CLI和Apache mod上运行了它:
I'm experiencing odd behavior with json_encode
after removing a numeric array key with unset
. The following code should make the problem clear. I've run it from both the CLI and as an Apache mod:
PHP版本信息:
C:\Users\usr\Desktop>php -v
PHP 5.3.1 (cli) (built: Nov 20 2009 17:26:32)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
PHP代码
<?php
$a = array(
new stdclass,
new stdclass,
new stdclass
);
$a[0]->abc = '123';
$a[1]->jkl = '234';
$a[2]->nmo = '567';
printf("%s\n", json_encode($a));
unset($a[1]);
printf("%s\n", json_encode($a));
程序输出
C:\Users\usr\Desktop>php test.php
[{"abc":"123"},{"jkl":"234"},{"nmo":"567"}]
{"0":{"abc":"123"},"2":{"nmo":"567"}}
如您所见,第一次将$a
转换为JSON时,它被编码为javascript数组.第二次(在unset
调用之后)$a
被编码为javascript对象.为什么会这样,我该如何预防呢?
As you can see, the first time $a
is converted to JSON it's encoded as a javascript array. The second time around (after the unset
call) $a
is encoded as a javascript object. Why is this and how can I prevent it?
推荐答案
这样做的原因是您的数组中有一个孔:它的索引为0和2,但缺少1.JSON无法使用以下格式对数组进行编码漏洞,因为数组语法不支持索引.
The reason for that is that your array has a hole in it: it has the indices 0 and 2, but misses 1. JSON can't encode arrays with holes because the array syntax has no support for indices.
您可以对 array_values($a)
进行编码,这将返回一个重新索引的数组.
You can encode array_values($a)
instead, which will return a reindexed array.
这篇关于PHP数组unset()之后,PHP json_encode作为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!