PHP数组unset()之后,PHP json_encode作为对象 [英] PHP json_encode as object after PHP array unset()

查看:267
本文介绍了PHP数组unset()之后,PHP json_encode作为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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屋!

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