PHP“警告:...中存在非法偏移类型”数组问题让我难住了
我在试图弄清楚为什么我的阵列没有按预期工作时遇到了很大的麻烦。我使用的代码在功能上与下面的代码相同,但它在我的程序中默默地失败了,因此我使用相同类型的数据和语法编写了一个单独的测试用例,并得到了有关非法偏移类型的错误。
Warning: Illegal offset type in <file location>\example.php on line 12
Warning: Illegal offset type in <file location>\example.php on line 16
这些具体指的是包含对“$questions[$question]”的引用的两行。
<?php
$questions = array(
"訓読み: 玉"=>array("たま","だま"),
"訓読み: 立"=>array("たて","たち","たつ","たてる","だてる","だて"),
);
$question = $questions["訓読み: 立"];
if (is_array($questions[$question])){
$res = $questions[$question][0];
} else {
$res = $questions[$question];
}
echo $res;
?>
我认为我超出了我的技能水平,因为虽然我可以看到 http://php.net/manual/en/language.types.array.php 指出“数组和对象不能用作键。这样做将导致警告:非法偏移type.",我看不出我正在做的事情与该页面上的示例 #7 有什么不同。
我非常感谢能够帮助我理解和解决我的问题的解释。
先感谢您!
I've been having considerable trouble trying to figure out why my arrays weren't working as expected. I was using code functionally the same as the code below, but it was silently failing on me in my program, so I wrote an isolated test case using the same types of data and syntax and got the errors about illegal offset types.
Warning: Illegal offset type in <file location>\example.php on line 12
Warning: Illegal offset type in <file location>\example.php on line 16
Those refer to the two lines containing the reference to "$questions[$question]" specifically.
<?php
$questions = array(
"訓読み: 玉"=>array("たま","だま"),
"訓読み: 立"=>array("たて","たち","たつ","たてる","だてる","だて"),
);
$question = $questions["訓読み: 立"];
if (is_array($questions[$question])){
$res = $questions[$question][0];
} else {
$res = $questions[$question];
}
echo $res;
?>
I think I'm just beyond my skill level here, because while I can see the warning on http://php.net/manual/en/language.types.array.php that states "Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.", I cannot see how what I'm doing is any different than Example #7 on that very page.
I would greatly appreciate an explanation that would help me understand and solve my problem here.
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用
$question = $questions["训読み: 立"];
时,您将收到该字符串表示的数组。当您使用 $questions[$question] 时,您应该只使用 $question:When you call
$question = $questions["訓読み: 立"];
, you are receiving the array represented by that string. When you use $questions[$question], you should just be using $question:要消除警告,您必须在调用 is_array 之前使用 array_key_exists 进行额外检查
它应该看起来像这样:
它应该完成这项工作
to get rid of the warn you must do additional check before callind is_array by using array_key_exists
it should look something like that:
it should do the job
据我所知,他们在手册页上没有这样做。您不能使用数组作为键。
They don't do that on the manual page as far as I can see. You can't use arrays as keys.