在数组中设置键/值“不能将标量值用作数组”

时间:2015-01-27 23:15:18

标签: php arrays

我有一个包含这些数据的数组var:

  $arr["values"] = [
    "key1" => "value1"
    "key2" => "value2"
    "key3" => "value3"
  ]

现在我尝试向$arr添加新密钥,如下所示:

$arr['newvalues'] = "anothervalue";
$arr['newvalues']['subvalues'] = "some_subvalue";

但我收到了这个错误:

  

警告:不能将标量值用作数组

此行标记错误:

$arr['newvalues']['subvalues'] = "some_subvalue";

为什么呢?我没有正确添加键/值?我做错了什么?

2 个答案:

答案 0 :(得分:1)

在这一行

$arr['newvalues'] = "anothervalue";

您正在为$arr['newvalues']分配标量值。在下一行中,您将它视为一个数组,但它不是因为您只是为它指定了一个标量值。

可能意味着让$arr['newvalues']成为一个数组并向其添加anothervalue

$arr['newvalues'][] = "anothervalue";

答案 1 :(得分:1)

您必须将$arr['newvalues']设置为数组以向其添加元素,目前您将其设置为字符串。

$arr['newvalues'] = [];
$arr['newvalues']['subvalues'] = "some_subvalue";