致命错误:未捕获错误:无法使用标量作为数组警告
我有以下代码:
$final = [1 => 2];
$id = 1;
$final[$id][0] = 3;
该代码似乎工作正常,但我收到此警告:
警告:无法在第 X 行中将标量值用作数组( 符合:$final[$id][0] = 3)。
谁能告诉我如何解决这个问题?
I have the following code:
$final = [1 => 2];
$id = 1;
$final[$id][0] = 3;
The code seems to work fine, but I get this warning:
Warning: Cannot use a scalar value as an array in line X (the
line with: $final[$id][0] = 3).
Can anyone tell me how to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在向数组添加元素之前,您需要将
$final[$id]
设置为数组。使用或初始化它
You need to set
$final[$id]
to an array before adding elements to it. Intiialize it with eitheror
原因是因为您首先在某个地方使用普通整数或字符串声明了变量,然后尝试将其转换为数组。
The reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.
我在这方面看到的另一个问题是,当嵌套数组时,这往往会引发警告,请考虑以下事项:
上面的内容在使用时绝对可以正常工作,例如:
但下面的内容会引发警告 ::
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
this above will work absolutely fine when used like:
But the below will throw a warning ::
还要确保您没有将其声明为数组,然后尝试将其他内容分配给该数组,例如字符串、浮点数、整数。我有这个问题。如果你对输出进行一些回显,我第一次就会看到我想要的东西,但在另一遍相同的代码之后就不会了。
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.