[英]Why does accessing an array element throw an array-as-string error in PHP?
I've done some searching and I didn't find any posts that quite answered my question. 我已经进行了一些搜索,但没有找到能完全回答我问题的帖子。 I have a PHP array generated, for the sake of argument, with this code: 为了论证,我使用以下代码生成了一个PHP数组:
$i = 5;
for($i = 0; $i < $j; $i++) {
$multiArray[0][$i] = $i;
$multiArray[1][$i] = $i;
}
When I try to access it with: 当我尝试通过以下方式访问它时:
for($i = 0; $i < $j; $i++) {
echo "$multiArray[0][$i]";
echo "$multiArray[1][$i]";
}
I get: 我得到:
Notice: Array to string conversion on line 3 注意:第3行中的数组到字符串的转换
Notice: Array to string conversion on line 4 注意:第4行中的数组到字符串的转换
...x4 ... x4
When I replace echo
with printf("%d", $multiArray[0][$i])
then it prints fine. 当我用printf("%d", $multiArray[0][$i])
代替echo
,它可以正常打印。 Why do I have to explicitly tell PHP that I'm asking for an int when the element I'm accessing is clearly an int (and PHP knows it, via var_dump()
)? 当要访问的元素显然是int时(为什么PHP可以通过var_dump()
知道),为什么我必须明确地告诉PHP我要的是int? I'm not accessing the array, but an element within the array. 我不访问数组,但数组中的元素。
Thanks 谢谢
Simple double quoted variable interpolation supports up to one nested element. 简单的双引号变量插值最多支持一个嵌套元素。 In other words, "foo[0][1]"
is interpreted as "{$foo[0]}[1]"
. 换句话说, "foo[0][1]"
被解释为"{$foo[0]}[1]"
。 That means it tries to interpret the array $foo[0]
as a string at that point to interpolate it into the string. 这意味着它将尝试将数组$foo[0]
为字符串,以将其内插到字符串中。
But using quotes here at all is entirely nonsensical. 但是,在这里使用引号完全是荒谬的。 You don't want string interpolation, you just want to output a variable value: 您不需要字符串插值,只想输出一个变量值:
echo $multiArray[0][$i];
just try this: 尝试一下:
for($i = 0; $i < $j; $i++) {
echo $multiArray[0][$i];
echo $multiArray[1][$i];
}
Your code is parsing the string not the array, try to remove the quotes.The [] brackets after the array are considered as a string not the as a paremeter.Use the code below 您的代码正在解析字符串而不是数组,请尝试删除引号。数组后的[]括号被视为字符串,而不是作为参数。使用以下代码
<?php
$j = 5;
for($i = 0; $i < $j; $i++) {
$multiArray[0][$i] = $i;
$multiArray[1][$i] = $i;
}
for($i = 0; $i < $j; $i++) {
echo $multiArray[1][$i];
}
Hope this helps you 希望这对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.