PHP:对象类型转换为数组后,奇怪的数组行为 [英] PHP: Strange Array Behaviour After Object Type Casting to Array

查看:161
本文介绍了PHP:对象类型转换为数组后,奇怪的数组行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您执行 array 类型转换为 json_decode d值时(使用 $ assoc = false ),PHP创建带有字符串索引的数组:

When you do array type-casting of json_decoded value (with $assoc = false), PHP creates an array with string indices:

$a = (array)json_decode('{"7":"value1","8":"value2","9":"value3","13":"value4"}');

var_export($a);

//array (
//  '7' => 'value1',
//  '8' => 'value2',
//  '9' => 'value3',
//  '13' => 'value4',
//)

由于某种原因,这些索引不可访问:

And for some reason these indices are not accessible:

var_dump(isset($a[7]), isset($a['7']));

//false
//false

尝试要通过PHP本身创建相同的数组,将使用数字索引创建该数组(自动转换字符串),并且可以使用字符串和数字访问值:

When you try to create the same array by PHP itself, it is being created with numeric indices (string are automatically converted), and values are accessible using both strings and numbers:

$c = array('7' => 'value1', '8' => 'value2', '9' => 'value3','10' => 'value4');

var_export($c);

var_dump(isset($c[7]), isset($c['7']));

//array (
//  7 => 'value1',
//  8 => 'value2',
//  9 => 'value3',
//  13 => 'value4',
//)
//
//true
//true

有人知道这里发生了什么吗?这是旧PHP版本的一些错误吗(此问题似乎已在PHP版本> = 7.2上解决,但我在更改日志)?

Does anybody know what is going on here? Is it some bug of older PHP versions (the issue seems to be fixed on PHP version >= 7.2, but I can't find anything related in changelog)?

这是正在发生的事情的演示: https://3v4l.org/da9CJ

Here's the demo of what is going on: https://3v4l.org/da9CJ.

推荐答案

这似乎与错误#61655 有关7.2.0:

This seems to be related to bug #61655 fixed in 7.2.0:


在对象属性中按名称查找总是在字符串中,但在数组数字
字符串中(例如 22200 )键将转换为数字,但不再转换为字符串。
,当转换内部HashTable不变时,因此转换后,键
查找将失败。

in a object property lookup by name always in string, but in array numeric string(like "22200" ) key will transform to numeric but not a string anymore. when conversion internal HashTable did't changed so after conversion, key lookup will fail.

已澄清: $ a [ 2000] 始终被解释为 $ a [2000] ,但 (数组)无法将对象字符串键转换为数字。因此数组包含字符串数字索引,但是数组语法的自动强制转换阻止了这些字符串的访问。

Clarified: $a["2000"] is always interpreted as $a[2000], but (array) failed to cast object string keys to numbers. So the array contained string numeric indices, but the array syntax' automatic casting prevented those from being accessible.

这篇关于PHP:对象类型转换为数组后,奇怪的数组行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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