0

我像这样添加我的会话变量:

foreach ( $data as $key => $value ) {
  $this->Session->write("MyVariable.$key", $value );
}

是否可以在不传递密钥的情况下将元素添加到会话变量数组?
我的意思是这样的:

$MyArray[] = "apple";
$MyArray[] = "banana";

那么可以这样添加吗?伪代码:

$this->Session->write('MyVariable'.[], "apple");
$this->Session->write('MyVariable'.[], "banana");

编辑:$data数组是为了举例。将要保存的数据不是数组。它是一个字符串。每次我添加到会话变量时,我都不想通过代码提供密钥。我想知道是否可以开箱即用。在我当前的代码中,我是这样写的:

    $newKey = count( $this->Session->read("MyVariable") );
    $this->Session->write("MyVariable.$newKey", "apple");
4

2 回答 2

0

嗨,我想应该是这样的:

foreach ( $data as $key => $value ) {
  $this->Session->write('MyVariable.'.$key, $value );
}

您必须在引号内放置一个点。

于 2013-06-06T11:46:07.940 回答
0

如果您不想每次都给出键值,则将其存储为数组,如@mark 所说

$this->Session->write("MyVariable", $data);

如果要在代码的其他部分向 $data 数组添加新值,则必须执行类似的操作

$data = $this->Session->read("MyVariable");
$data[] = array('other'=>'value');
$this->Session->write("MyVariable", $data);

或者像@mmahgoub 说的那样添加确切的密钥

$this->Session->write("MyVariable".$key, $value);
于 2013-06-06T13:27:37.670 回答