PHP/Hack中读取嵌套字典遇索引类型无效错误的问题排查
嵌套关联数组字符串索引报错问题解决
问题重现
我尝试创建一个简单的嵌套关联数组并读取其中的嵌套值,编写了如下代码:
$response = dict[ 'some_other_key' => 'asdf', 'sub_response' => dict['success' => false], ]; if ($response['sub_response']['success']){ // do stuff }
但遇到了如下错误:
Typing[4324] Invalid index type for this array [1]
-> Expected int [2]
-> This can only be indexed with integers [3]
-> But got string [2]40 | 41 | $response = dict[[3] 42 | 'some_other_key' => 'asdf',
43 | 'sub_response' => dict['success' => false],
44 | ];
45 |
[1,2] 46 | if ($response['sub_response']['success']) {
47 | return $response;
48 | }1 error found.
错误提示抱怨使用了字符串索引,请问哪里操作出错了?
问题原因与解决方案
问题根源
PHP里没有dict这个关键字,你混淆了其他语言(比如Python)的语法。dict[]会被解释器错误识别为创建整数索引数组的写法,而你实际要创建的是支持字符串键的关联数组,所以后续用字符串键访问时触发了类型检查错误。
修正代码
直接用[]语法创建关联数组即可:
$response = [ 'some_other_key' => 'asdf', 'sub_response' => ['success' => false], ]; if ($response['sub_response']['success']){ // do stuff }
补充说明
- 在PHP中,
[]是创建数组的标准语法:当你用=>指定键值对时,自动创建关联数组;如果只写元素值,则创建整数索引的索引数组。 - 旧版本PHP也可以用
array()语法,比如array('some_other_key' => 'asdf'),效果和[]一致。
内容的提问来源于stack exchange,提问作者kneighbor
相关产品推荐
相关产品推荐

