致命错误:未捕获错误:无法使用标量作为数组警告

发布于 2024-11-07 09:18:28 字数 222 浏览 0 评论 0原文

我有以下代码:

 $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

谜泪 2024-11-14 09:18:28

在向数组添加元素之前,您需要将$final[$id] 设置为数组。使用

$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];

或初始化它

$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];

You need to set$final[$id] to an array before adding elements to it. Intiialize it with either

$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];

or

$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
黎夕旧梦 2024-11-14 09:18:28

原因是因为您首先在某个地方使用普通整数或字符串声明了变量,然后尝试将其转换为数组。

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.

秋千易 2024-11-14 09:18:28

我在这方面看到的另一个问题是,当嵌套数组时,这往往会引发警告,请考虑以下事项:

$data = [
"rs" => null
]

上面的内容在使用时绝对可以正常工作,例如:

$data["rs"] =  5;

但下面的内容会引发警告 ::

$data = [
    "rs" => [
       "rs1" => null;
       ]
    ]
..

$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array

The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:

$data = [
"rs" => null
]

this above will work absolutely fine when used like:

$data["rs"] =  5;

But the below will throw a warning ::

$data = [
    "rs" => [
       "rs1" => null;
       ]
    ]
..

$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
呆头 2024-11-14 09:18:28

还要确保您没有将其声明为数组,然后尝试将其他内容分配给该数组,例如字符串、浮点数、整数。我有这个问题。如果你对输出进行一些回显,我第一次就会看到我想要的东西,但在另一遍相同的代码之后就不会了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文