Php 在数组的数组中添加数组

Php 在数组的数组中添加数组,php,Php,我有一个名为“items”的$\u会话索引。 就这样, { 0: { id: "1", ref: "0001", }, id: "2", ref: "0001", } $_会话['items'] 当用户单击添加项目时,我会检查$\u会话['items']是否存在。如果存在,则插入该项;如果不存在,则创建并插入。嗯 所以我对这个解决方案进行了编码: $newItem = array( 'id'=>$this->getId(), 'red'=>$this->

我有一个名为“items”的$\u会话索引。 就这样,

{
0: {
id: "1",
ref: "0001",
},
id: "2",
ref: "0001",
}
$_会话['items']

当用户单击添加项目时,我会检查$\u会话['items']是否存在。如果存在,则插入该项;如果不存在,则创建并插入。嗯

所以我对这个解决方案进行了编码:

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

if(isset($_SESSION['items'])) {
    array_push($_SESSION['items'],$newItem);
} else {
    $_SESSION['items'] = $newItem;
}
嗯。 问题是: 如果出现“else”,则$newItem数组将被推入具有以下结构的$\u会话['items']:

{
0: {
id: "1",
ref: "0001",
}
}
正如我所期待的那样。 但是,如果出现“if”语句,我的$u会话['item']将释放新的索引,我将得到如下结构:

{
0: {
id: "1",
ref: "0001",
},
id: "2",
ref: "0001",
}
如您所见,新项未设置为数组。。。 如果我添加更多ITEN,问题只影响最后添加的项目


我做错了什么?

将代码更改为以下内容:

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"
    }
  }
}
现场示例


-使用了虚拟数据

您的数组在这里推送似乎有问题,因为当您在$\u会话['items']中推送数组时,它会接受$newItem数组元素并在$\u会话['items']中推送它们

如果你能做到以下几点,那么它应该会起作用

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