在数组数组中添加数组

时间:2018-06-07 03:42:00

标签: php

我有一个名为“items”的$ _SESSION索引。 就像这样:

$ _ SESSION [ '项'];

当用户点击添加项目时,我会检查$ _SESSION ['items']是否存在。如果存在,则插入项目,如果不存在,则创建并插入。确定。

所以我编写了这个解决方案:

$newItem = array(
    'id'=>$this->getId(),
    'red'=>$this->getRef()
);

if(isset($_SESSION['items'])) {
    array_push($_SESSION['items'],$newItem);
} else {
    $_SESSION['items'] = $newItem;
}

确定。 问题是: 如果发生“else”,则将$ newItem数组推入具有以下结构的$ _SESSION ['items']:

{
0: {
id: "1",
ref: "0001",
}
}

正如我所期待的那样。 但是如果发生“if”语句,我的$ _SESSION ['item']会丢失新索引,我会得到这样的结构:

{
0: {
id: "1",
ref: "0001",
},
id: "2",
ref: "0001",
}

如您所见,新项目未设置为数组... 如果我添加更多itens,则问题仅影响最后添加的项目...

我做错了什么?

2 个答案:

答案 0 :(得分:0)

将您的代码更改为以下内容:

if (isset($_SESSION['items'])) {
    array_push($_SESSION['items'],$newItem);
} else {
    $_SESSION['items'] = [];

    array_push($_SESSION['items'], $newItem);
}

现在,所有$newItems都将被推送到实际的数组中。

<强>输出

array(1) {
  ["items"]=>
  array(2) {
    [0]=>
    array(2) {
      ["id"]=>
      string(2) "id"
      ["ref"]=>
      string(3) "ref"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(4) "id-2"
      ["ref"]=>
      string(5) "ref-2"
    }
  }
}

直播示例

Repl - 使用虚拟数据

答案 1 :(得分:0)

你的array_push似乎有问题,因为当你在$ _SESSION ['items']中推送数组时,需要$ newItem数组元素并将它们推送到$ _SESSION ['items']

如果您可以执行以下操作,那么它应该可以正常工作

$newItem = array(
'id'=>$this->getId(),
    'red'=>$this->getRef()
);
$_SESSION['items'][]= $newItem;
相关问题